~ntt-pf-lab/nova/monkey_patch_notification

« back to all changes in this revision

Viewing changes to vendor/boto/bin/launch_instance

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# Copyright (c) 2009 Chris Moyer http://coredumped.org/
 
3
#
 
4
# Permission is hereby granted, free of charge, to any person obtaining a
 
5
# copy of this software and associated documentation files (the
 
6
# "Software"), to deal in the Software without restriction, including
 
7
# without limitation the rights to use, copy, modify, merge, publish, dis-
 
8
# tribute, sublicense, and/or sell copies of the Software, and to permit
 
9
# persons to whom the Software is furnished to do so, subject to the fol-
 
10
# lowing conditions:
 
11
#
 
12
# The above copyright notice and this permission notice shall be included
 
13
# in all copies or substantial portions of the Software.
 
14
#
 
15
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 
16
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
 
17
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
 
18
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
 
19
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 
20
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 
21
 
 
22
#
 
23
# Utility to launch an EC2 Instance
 
24
#
 
25
VERSION="0.1"
 
26
 
 
27
import boto.pyami.config
 
28
from boto.utils import fetch_file
 
29
import re, os
 
30
import ConfigParser
 
31
 
 
32
class Config(boto.pyami.config.Config):
 
33
    """A special config class that also adds import abilities
 
34
    Directly in the config file. To have a config file import
 
35
    another config file, simply use "#import <path>" where <path>
 
36
    is either a relative path or a full URL to another config
 
37
    """
 
38
 
 
39
    def __init__(self):
 
40
        ConfigParser.SafeConfigParser.__init__(self, {'working_dir' : '/mnt/pyami', 'debug' : '0'})
 
41
 
 
42
    def add_config(self, file_url):
 
43
        """Add a config file to this configuration
 
44
        :param file_url: URL for the file to add, or a local path
 
45
        :type file_url: str
 
46
        """
 
47
        if not re.match("^([a-zA-Z0-9]*:\/\/)(.*)", file_url):
 
48
            if not file_url.startswith("/"):
 
49
                file_url = os.path.join(os.getcwd(), file_url)
 
50
            file_url = "file://%s" % file_url
 
51
        (base_url, file_name) = file_url.rsplit("/", 1)
 
52
        base_config = fetch_file(file_url)
 
53
        base_config.seek(0)
 
54
        for line in base_config.readlines():
 
55
            match = re.match("^#import[\s\t]*([^\s^\t]*)[\s\t]*$", line)
 
56
            if match:
 
57
                self.add_config("%s/%s" % (base_url, match.group(1)))
 
58
        base_config.seek(0)
 
59
        self.readfp(base_config)
 
60
 
 
61
    def add_creds(self, ec2):
 
62
        """Add the credentials to this config if they don't already exist"""
 
63
        if not self.has_section('Credentials'):
 
64
            self.add_section('Credentials')
 
65
            self.set('Credentials', 'aws_access_key_id', ec2.aws_access_key_id)
 
66
            self.set('Credentials', 'aws_secret_access_key', ec2.aws_secret_access_key)
 
67
 
 
68
    
 
69
    def __str__(self):
 
70
        """Get config as string"""
 
71
        from StringIO import StringIO
 
72
        s = StringIO()
 
73
        self.write(s)
 
74
        return s.getvalue()
 
75
 
 
76
 
 
77
if __name__ == "__main__":
 
78
    try:
 
79
        import readline
 
80
    except ImportError:
 
81
        pass
 
82
    import boto
 
83
    from optparse import OptionParser
 
84
    from boto.mashups.iobject import IObject
 
85
    parser = OptionParser(version=VERSION, usage="%prog [options] config_url")
 
86
    parser.add_option("-c", "--max-count", help="Maximum number of this type of instance to launch", dest="max_count", default="1")
 
87
    parser.add_option("--min-count", help="Minimum number of this type of instance to launch", dest="min_count", default="1")
 
88
    parser.add_option("-g", "--groups", help="Security Groups to add this instance to",  action="append", dest="groups")
 
89
    parser.add_option("-a", "--ami", help="AMI to launch", dest="ami_id")
 
90
    parser.add_option("-t", "--type", help="Type of Instance (default m1.small)", dest="type", default="m1.small")
 
91
    parser.add_option("-k", "--key", help="Keypair", dest="key_name")
 
92
    parser.add_option("-z", "--zone", help="Zone (default us-east-1a)", dest="zone", default="us-east-1a")
 
93
    parser.add_option("-i", "--ip", help="Elastic IP", dest="elastic_ip")
 
94
    parser.add_option("-n", "--no-add-cred", help="Don't add a credentials section", default=False, action="store_true", dest="nocred")
 
95
 
 
96
    (options, args) = parser.parse_args()
 
97
 
 
98
    if len(args) < 1:
 
99
        import sys
 
100
        parser.print_help()
 
101
        sys.exit(1)
 
102
    file_url = os.path.expanduser(args[0])
 
103
    ec2 = boto.connect_ec2()
 
104
 
 
105
    cfg = Config()
 
106
    cfg.add_config(file_url)
 
107
    if not options.nocred:
 
108
        cfg.add_creds(ec2)
 
109
 
 
110
    iobj = IObject()
 
111
    if options.ami_id:
 
112
        ami = ec2.get_image(options.ami_id)
 
113
    else:
 
114
        ami_id = options.ami_id
 
115
        l = [(a, a.id, a.location) for a in ec2.get_all_images()]
 
116
        ami = iobj.choose_from_list(l, prompt='Choose AMI')
 
117
 
 
118
    if options.key_name:
 
119
        key_name = options.key_name
 
120
    else:
 
121
        l = [(k, k.name, '') for k in ec2.get_all_key_pairs()]
 
122
        key_name = iobj.choose_from_list(l, prompt='Choose Keypair').name
 
123
 
 
124
    if options.groups:
 
125
        groups = options.groups
 
126
    else:
 
127
        groups = []
 
128
        l = [(g, g.name, g.description) for g in ec2.get_all_security_groups()]
 
129
        g = iobj.choose_from_list(l, prompt='Choose Primary Security Group')
 
130
        while g != None:
 
131
            groups.append(g)
 
132
            l.remove((g, g.name, g.description))
 
133
            g = iobj.choose_from_list(l, prompt='Choose Additional Security Group (0 to quit)')
 
134
 
 
135
    r = ami.run(min_count=int(options.min_count), max_count=int(options.max_count),
 
136
            key_name=key_name, user_data=str(cfg),
 
137
            security_groups=groups, instance_type=options.type,
 
138
            placement=options.zone)