Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(2)

Side by Side Diff: third_party/gsutil/20110627/boto/bin/launch_instance

Issue 10199002: Upgrade gsutil to 3.4 (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Addressed comments Created 8 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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.2"
26
27
28 CLOUD_INIT_SCRIPT = """#!/usr/bin/env python
29 f = open("/etc/boto.cfg", "w")
30 f.write(\"\"\"%s\"\"\")
31 f.close()
32 """
33 import boto.pyami.config
34 import boto.utils
35 import re, os
36 import ConfigParser
37
38 class Config(boto.pyami.config.Config):
39 """A special config class that also adds import abilities
40 Directly in the config file. To have a config file import
41 another config file, simply use "#import <path>" where <path>
42 is either a relative path or a full URL to another config
43 """
44
45 def __init__(self):
46 ConfigParser.SafeConfigParser.__init__(self, {'working_dir' : '/mnt/pyam i', 'debug' : '0'})
47
48 def add_config(self, file_url):
49 """Add a config file to this configuration
50 :param file_url: URL for the file to add, or a local path
51 :type file_url: str
52 """
53 if not re.match("^([a-zA-Z0-9]*:\/\/)(.*)", file_url):
54 if not file_url.startswith("/"):
55 file_url = os.path.join(os.getcwd(), file_url)
56 file_url = "file://%s" % file_url
57 (base_url, file_name) = file_url.rsplit("/", 1)
58 base_config = boto.utils.fetch_file(file_url)
59 base_config.seek(0)
60 for line in base_config.readlines():
61 match = re.match("^#import[\s\t]*([^\s^\t]*)[\s\t]*$", line)
62 if match:
63 self.add_config("%s/%s" % (base_url, match.group(1)))
64 base_config.seek(0)
65 self.readfp(base_config)
66
67 def add_creds(self, ec2):
68 """Add the credentials to this config if they don't already exist"""
69 if not self.has_section('Credentials'):
70 self.add_section('Credentials')
71 self.set('Credentials', 'aws_access_key_id', ec2.aws_access_key_id)
72 self.set('Credentials', 'aws_secret_access_key', ec2.aws_secret_acce ss_key)
73
74
75 def __str__(self):
76 """Get config as string"""
77 from StringIO import StringIO
78 s = StringIO()
79 self.write(s)
80 return s.getvalue()
81
82
83 if __name__ == "__main__":
84 try:
85 import readline
86 except ImportError:
87 pass
88 import sys
89 import time
90 import boto
91 from boto.ec2 import regions
92 from optparse import OptionParser
93 from boto.mashups.iobject import IObject
94 parser = OptionParser(version=VERSION, usage="%prog [options] config_url")
95 parser.add_option("-c", "--max-count", help="Maximum number of this type of instance to launch", dest="max_count", default="1")
96 parser.add_option("--min-count", help="Minimum number of this type of instan ce to launch", dest="min_count", default="1")
97 parser.add_option("--cloud-init", help="Indicates that this is an instance t hat uses 'CloudInit', Ubuntu's cloud bootstrap process. This wraps the config in a shell script command instead of just passing it in directly", dest="cloud_ini t", default=False, action="store_true")
98 parser.add_option("-g", "--groups", help="Security Groups to add this instan ce to", action="append", dest="groups")
99 parser.add_option("-a", "--ami", help="AMI to launch", dest="ami_id")
100 parser.add_option("-t", "--type", help="Type of Instance (default m1.small)" , dest="type", default="m1.small")
101 parser.add_option("-k", "--key", help="Keypair", dest="key_name")
102 parser.add_option("-z", "--zone", help="Zone (default us-east-1a)", dest="zo ne", default="us-east-1a")
103 parser.add_option("-r", "--region", help="Region (default us-east-1)", dest= "region", default="us-east-1")
104 parser.add_option("-i", "--ip", help="Elastic IP", dest="elastic_ip")
105 parser.add_option("-n", "--no-add-cred", help="Don't add a credentials secti on", default=False, action="store_true", dest="nocred")
106 parser.add_option("--save-ebs", help="Save the EBS volume on shutdown, inste ad of deleting it", default=False, action="store_true", dest="save_ebs")
107 parser.add_option("-w", "--wait", help="Wait until instance is running", def ault=False, action="store_true", dest="wait")
108 parser.add_option("-d", "--dns", help="Returns public and private DNS (impli cates --wait)", default=False, action="store_true", dest="dns")
109 parser.add_option("-T", "--tag", help="Set tag", default=None, action="appen d", dest="tags", metavar="key:value")
110 parser.add_option("-s", "--add-script", help="Pass in a script or a folder c ontaining scripts to be run when the instance starts up, assumes cloud-init. If multiple scripts are specified, they are run in the order they were specified. I f they are in a folder, they are run in alphabetical order", default=None, dest= "scripts", action="append")
111
112 (options, args) = parser.parse_args()
113
114 if len(args) < 1:
115 parser.print_help()
116 sys.exit(1)
117 file_url = os.path.expanduser(args[0])
118
119 cfg = Config()
120 cfg.add_config(file_url)
121
122 for r in regions():
123 if r.name == options.region:
124 region = r
125 break
126 else:
127 print "Region %s not found." % options.region
128 sys.exit(1)
129 ec2 = boto.connect_ec2(region=region)
130 if not options.nocred:
131 cfg.add_creds(ec2)
132
133 iobj = IObject()
134 if options.ami_id:
135 ami = ec2.get_image(options.ami_id)
136 else:
137 ami_id = options.ami_id
138 l = [(a, a.id, a.location) for a in ec2.get_all_images()]
139 ami = iobj.choose_from_list(l, prompt='Choose AMI')
140
141 if options.key_name:
142 key_name = options.key_name
143 else:
144 l = [(k, k.name, '') for k in ec2.get_all_key_pairs()]
145 key_name = iobj.choose_from_list(l, prompt='Choose Keypair').name
146
147 if options.groups:
148 groups = options.groups
149 else:
150 groups = []
151 l = [(g, g.name, g.description) for g in ec2.get_all_security_groups()]
152 g = iobj.choose_from_list(l, prompt='Choose Primary Security Group')
153 while g != None:
154 groups.append(g)
155 l.remove((g, g.name, g.description))
156 g = iobj.choose_from_list(l, prompt='Choose Additional Security Grou p (0 to quit)')
157
158 user_data = str(cfg)
159 # If it's a cloud init AMI,
160 # then we need to wrap the config in our
161 # little wrapper shell script
162 if options.cloud_init:
163 user_data = CLOUD_INIT_SCRIPT % user_data
164 scriptuples = []
165 if options.scripts:
166 scripts = options.scripts
167 scriptuples.append(('user_data', user_data))
168 for scr in scripts:
169 scr_url = scr
170 if not re.match("^([a-zA-Z0-9]*:\/\/)(.*)", scr_url):
171 if not scr_url.startswith("/"):
172 scr_url = os.path.join(os.getcwd(), scr_url)
173 try:
174 newfiles = os.listdir(scr_url)
175 for f in newfiles:
176 #put the scripts in the folder in the array such tha t they run in the correct order
177 scripts.insert(scripts.index(scr) + 1, scr.split("/" )[-1] + "/" + f)
178 except OSError:
179 scr_url = "file://%s" % scr_url
180 try:
181 script_content = boto.utils.fetch_file(scr_url)
182 scriptuples.append((scr, script_content.read()))
183 except ValueError:
184 pass
185
186 user_data = boto.utils.write_mime_multipart(scriptuples, compress=Fa lse)
187
188 shutdown_proc = "terminate"
189 if options.save_ebs:
190 shutdown_proc = "save"
191
192 r = ami.run(min_count=int(options.min_count), max_count=int(options.max_coun t),
193 key_name=key_name, user_data=user_data,
194 security_groups=groups, instance_type=options.type,
195 placement=options.zone, instance_initiated_shutdown_behavior=shutdow n_proc)
196
197 instance = r.instances[0]
198
199 if options.tags:
200 for tag_pair in options.tags:
201 name = tag_pair
202 value = ''
203 if ':' in tag_pair:
204 name, value = tag_pair.split(':', 1)
205 instance.add_tag(name, value)
206
207 if options.dns:
208 options.wait = True
209
210 if not options.wait:
211 sys.exit(0)
212
213 while True:
214 instance.update()
215 if instance.state == 'running':
216 break
217 time.sleep(3)
218
219 if options.dns:
220 print "Public DNS name: %s" % instance.public_dns_name
221 print "Private DNS name: %s" % instance.private_dns_name
OLDNEW
« no previous file with comments | « third_party/gsutil/20110627/boto/bin/kill_instance ('k') | third_party/gsutil/20110627/boto/bin/list_instances » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698