redaranj-right_aws 1.11.1 → 1.11.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,373 @@
1
+ #
2
+ # Copyright (c) 2009 RightScale Inc
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a 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,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #
23
+
24
+ module RightAws
25
+
26
+ class Ec2
27
+
28
+ #-----------------------------------------------------------------
29
+ # Images
30
+ #-----------------------------------------------------------------
31
+
32
+ # Describe images helper
33
+ # params:
34
+ # { 'ImageId' => ['id1', ..., 'idN'],
35
+ # 'Owner' => ['self', ..., 'userN'],
36
+ # 'ExecutableBy' => ['self', 'all', ..., 'userN']
37
+ # }
38
+ def ec2_describe_images(params={}, image_type=nil, cache_for=nil) #:nodoc:
39
+ request_hash = {}
40
+ params.each do |list_by, list|
41
+ request_hash.merge! amazonize_list(list_by, list.to_a)
42
+ end
43
+ request_hash['ImageType'] = image_type if image_type
44
+ link = generate_request("DescribeImages", request_hash)
45
+ request_cache_or_info cache_for, link, QEc2DescribeImagesParser, @@bench, cache_for
46
+ rescue Exception
47
+ on_exception
48
+ end
49
+
50
+ # Retrieve a list of images. Returns array of hashes describing the images or an exception:
51
+ # +image_type+ = 'machine' || 'kernel' || 'ramdisk'
52
+ #
53
+ # ec2.describe_images #=>
54
+ # [{:aws_id=>"ami-b0a1f7a6",
55
+ # :aws_image_type=>"machine",
56
+ # :root_device_name=>"/dev/sda1",
57
+ # :image_class=>"static",
58
+ # :aws_owner=>"826693181925",
59
+ # :aws_location=>"bucket_for_k_dzreyev/image_bundles/kd__CentOS_1_10_2009_10_21_13_30_43_MSD/image.manifest.xml",
60
+ # :aws_state=>"available",
61
+ # :aws_is_public=>false,
62
+ # :aws_architecture=>"i386"},
63
+ # {:description=>"EBS backed Fedora core 8 i386",
64
+ # :aws_architecture=>"i386",
65
+ # :aws_id=>"ami-c2a3f5d4",
66
+ # :aws_image_type=>"machine",
67
+ # :root_device_name=>"/dev/sda1",
68
+ # :image_class=>"elastic",
69
+ # :aws_owner=>"937766719418",
70
+ # :aws_location=>"937766719418/EBS backed FC8 i386",
71
+ # :aws_state=>"available",
72
+ # :block_device_mappings=>
73
+ # [{:ebs_snapshot_id=>"snap-829a20eb",
74
+ # :ebs_delete_on_termination=>true,
75
+ # :device_name=>"/dev/sda1"}],
76
+ # :name=>"EBS backed FC8 i386",
77
+ # :aws_is_public=>true}, ... ]
78
+ #
79
+ # If +list+ param is set, then retrieve information about the listed images only:
80
+ #
81
+ # ec2.describe_images(['ami-5aa1f74c'])
82
+ #
83
+ def describe_images(list=[], image_type=nil)
84
+ list = list.to_a
85
+ cache_for = list.empty? && !image_type ? :describe_images : nil
86
+ ec2_describe_images({ 'ImageId' => list }, image_type, cache_for)
87
+ end
88
+
89
+ # Example:
90
+ #
91
+ # ec2.describe_images_by_owner('522821470517')
92
+ # ec2.describe_images_by_owner('self')
93
+ #
94
+ def describe_images_by_owner(list=['self'], image_type=nil)
95
+ list = list.to_a
96
+ cache_for = list==['self'] && !image_type ? :describe_images_by_owner : nil
97
+ ec2_describe_images({ 'Owner' => list }, image_type, cache_for)
98
+ end
99
+
100
+ # Example:
101
+ #
102
+ # ec2.describe_images_by_executable_by('522821470517')
103
+ # ec2.describe_images_by_executable_by('self')
104
+ # ec2.describe_images_by_executable_by('all')
105
+ #
106
+ def describe_images_by_executable_by(list=['self'], image_type=nil)
107
+ list = list.to_a
108
+ cache_for = list==['self'] && !image_type ? :describe_images_by_executable_by : nil
109
+ ec2_describe_images({ 'ExecutableBy' => list }, image_type, cache_for)
110
+ end
111
+
112
+
113
+ # Register new image at Amazon.
114
+ # Options: :image_location, :name, :description, :architecture, :kernel_id, :ramdisk_id, :root_device_name, :block_device_mappings.
115
+ #
116
+ # Returns new image id.
117
+ #
118
+ # # Register S3 image
119
+ # ec2.register_image('bucket_for_k_dzreyev/image_bundles/kd__CentOS_1_10_2009_10_21_13_30_43_MSD/image.manifest.xml') #=> 'ami-e444444d'
120
+ #
121
+ # # or
122
+ # image_reg_params = { :image_location => 'bucket_for_k_dzreyev/image_bundles/kd__CentOS_1_10_2009_10_21_13_30_43_MSD/image.manifest.xml',
123
+ # :name => 'my-test-one-1',
124
+ # :description => 'My first test image' }
125
+ # ec2.register_image(image_reg_params) #=> "ami-bca1f7aa"
126
+ #
127
+ # # Register EBS image
128
+ # image_reg_params = { :name => 'my-test-image',
129
+ # :description => 'My first test image',
130
+ # :root_device_name => "/dev/sda1",
131
+ # :block_device_mappings => [ { :ebs_snapshot_id=>"snap-7360871a",
132
+ # :ebs_delete_on_termination=>true,
133
+ # :device_name=>"/dev/sda1"} ] }
134
+ # ec2.register_image(image_reg_params) #=> "ami-b2a1f7a4"
135
+ #
136
+ def register_image(options)
137
+ case
138
+ when options.is_a?(String)
139
+ options = { :image_location => options }
140
+ when !options.is_a?(Hash)
141
+ raise "Unsupported options type"
142
+ end
143
+ params = {}
144
+ params['ImageLocation'] = options[:image_location] if options[:image_location]
145
+ params['Name'] = options[:name] if options[:name]
146
+ params['Description'] = options[:description] if options[:description]
147
+ params['Architecture'] = options[:architecture] if options[:architecture]
148
+ params['KernelId'] = options[:kernel_id] if options[:kernel_id]
149
+ params['RamdiskId'] = options[:ramdisk_id] if options[:ramdisk_id]
150
+ params['RootDeviceName'] = options[:root_device_name] if options[:root_device_name]
151
+ # params['SnapshotId'] = options[:snapshot_id] if options[:snapshot_id]
152
+ params.merge!(amazonize_block_device_mappings(options[:block_device_mappings]))
153
+ link = generate_request("RegisterImage", params)
154
+ request_info(link, QEc2RegisterImageParser.new(:logger => @logger))
155
+ rescue Exception
156
+ on_exception
157
+ end
158
+
159
+ # Deregister image at Amazon. Returns +true+ or an exception.
160
+ #
161
+ # ec2.deregister_image('ami-e444444d') #=> true
162
+ #
163
+ def deregister_image(image_id)
164
+ link = generate_request("DeregisterImage",
165
+ 'ImageId' => image_id.to_s)
166
+ request_info(link, RightBoolResponseParser.new(:logger => @logger))
167
+ rescue Exception
168
+ on_exception
169
+ end
170
+
171
+ # Describe image attributes. Currently 'launchPermission', 'productCodes', 'kernel', 'ramdisk' and 'blockDeviceMapping' are supported.
172
+ #
173
+ # ec2.describe_image_attribute('ami-e444444d') #=> {:groups=>["all"], :users=>["000000000777"]}
174
+ #
175
+ def describe_image_attribute(image_id, attribute='launchPermission')
176
+ link = generate_request("DescribeImageAttribute",
177
+ 'ImageId' => image_id,
178
+ 'Attribute' => attribute)
179
+ request_info(link, QEc2DescribeImageAttributeParser.new(:logger => @logger))
180
+ rescue Exception
181
+ on_exception
182
+ end
183
+
184
+ # Reset image attribute. Currently, only 'launchPermission' is supported. Returns +true+ or an exception.
185
+ #
186
+ # ec2.reset_image_attribute('ami-e444444d') #=> true
187
+ #
188
+ def reset_image_attribute(image_id, attribute='launchPermission')
189
+ link = generate_request("ResetImageAttribute",
190
+ 'ImageId' => image_id,
191
+ 'Attribute' => attribute)
192
+ request_info(link, RightBoolResponseParser.new(:logger => @logger))
193
+ rescue Exception
194
+ on_exception
195
+ end
196
+
197
+ # Modify an image's attributes. It is recommended that you use
198
+ # modify_image_launch_perm_add_users, modify_image_launch_perm_remove_users, etc.
199
+ # instead of modify_image_attribute because the signature of
200
+ # modify_image_attribute may change with EC2 service changes.
201
+ #
202
+ # attribute : currently, only 'launchPermission' is supported.
203
+ # operation_type : currently, only 'add' & 'remove' are supported.
204
+ # vars:
205
+ # :user_group : currently, only 'all' is supported.
206
+ # :user_id
207
+ # :product_code
208
+ def modify_image_attribute(image_id, attribute, operation_type = nil, vars = {})
209
+ params = {'ImageId' => image_id,
210
+ 'Attribute' => attribute}
211
+ params['OperationType'] = operation_type if operation_type
212
+ params.update(amazonize_list('UserId', vars[:user_id].to_a)) if vars[:user_id]
213
+ params.update(amazonize_list('UserGroup', vars[:user_group].to_a)) if vars[:user_group]
214
+ params.update(amazonize_list('ProductCode', vars[:product_code])) if vars[:product_code]
215
+ link = generate_request("ModifyImageAttribute", params)
216
+ request_info(link, RightBoolResponseParser.new(:logger => @logger))
217
+ rescue Exception
218
+ on_exception
219
+ end
220
+
221
+ # Grant image launch permissions to users.
222
+ # Parameter +user_id+ is a list of user AWS account ids.
223
+ # Returns +true+ or an exception.
224
+ #
225
+ # ec2.modify_image_launch_perm_add_users('ami-e444444d',['000000000777','000000000778']) #=> true
226
+ def modify_image_launch_perm_add_users(image_id, user_id=[])
227
+ modify_image_attribute(image_id, 'launchPermission', 'add', :user_id => user_id.to_a)
228
+ end
229
+
230
+ # Revokes image launch permissions for users. +user_id+ is a list of users AWS accounts ids. Returns +true+ or an exception.
231
+ #
232
+ # ec2.modify_image_launch_perm_remove_users('ami-e444444d',['000000000777','000000000778']) #=> true
233
+ #
234
+ def modify_image_launch_perm_remove_users(image_id, user_id=[])
235
+ modify_image_attribute(image_id, 'launchPermission', 'remove', :user_id => user_id.to_a)
236
+ end
237
+
238
+ # Add image launch permissions for users groups (currently only 'all' is supported, which gives public launch permissions).
239
+ # Returns +true+ or an exception.
240
+ #
241
+ # ec2.modify_image_launch_perm_add_groups('ami-e444444d') #=> true
242
+ #
243
+ def modify_image_launch_perm_add_groups(image_id, user_group=['all'])
244
+ modify_image_attribute(image_id, 'launchPermission', 'add', :user_group => user_group.to_a)
245
+ end
246
+
247
+ # Remove image launch permissions for users groups (currently only 'all' is supported, which gives public launch permissions).
248
+ #
249
+ # ec2.modify_image_launch_perm_remove_groups('ami-e444444d') #=> true
250
+ #
251
+ def modify_image_launch_perm_remove_groups(image_id, user_group=['all'])
252
+ modify_image_attribute(image_id, 'launchPermission', 'remove', :user_group => user_group.to_a)
253
+ end
254
+
255
+ # Add product code to image
256
+ #
257
+ # ec2.modify_image_product_code('ami-e444444d','0ABCDEF') #=> true
258
+ #
259
+ def modify_image_product_code(image_id, product_code=[])
260
+ modify_image_attribute(image_id, 'productCodes', nil, :product_code => product_code.to_a)
261
+ end
262
+
263
+ # Create a new image.
264
+ # Options: :name, :description, :no_reboot(bool)
265
+ #
266
+ # ec2.create_image(instance, :description => 'KD: test#1',
267
+ # :no_reboot => true,
268
+ # :name => 'kd-1' ) #=> "ami-84a1f792"
269
+ #
270
+ def create_image(instance_aws_id, options={})
271
+ params = { 'InstanceId' => instance_aws_id }
272
+ params['Name'] = options[:name] unless options[:name].blank?
273
+ params['Description'] = options[:description] unless options[:description].blank?
274
+ params['NoReboot'] = options[:no_reboot].to_s unless options[:no_reboot].nil?
275
+ link = generate_request("CreateImage", params)
276
+ request_info(link, QEc2RegisterImageParser.new(:logger => @logger))
277
+ end
278
+
279
+ #-----------------------------------------------------------------
280
+ # PARSERS: Images
281
+ #-----------------------------------------------------------------
282
+
283
+ class QEc2DescribeImagesParser < RightAWSParser #:nodoc:
284
+ def tagstart(name, attributes)
285
+ case full_tag_name
286
+ when %r{/imagesSet/item$} then @item = {}
287
+ when %r{/blockDeviceMapping/item$}
288
+ @item[:block_device_mappings] ||= []
289
+ @block_device_mapping = {}
290
+ end
291
+ end
292
+ def tagend(name)
293
+ case name
294
+ when 'imageId' then @item[:aws_id] = @text
295
+ when 'imageLocation' then @item[:aws_location] = @text
296
+ when 'imageState' then @item[:aws_state] = @text
297
+ when 'imageOwnerId' then @item[:aws_owner] = @text
298
+ when 'isPublic' then @item[:aws_is_public] = @text == 'true' ? true : false
299
+ when 'productCode' then (@item[:aws_product_codes] ||= []) << @text
300
+ when 'architecture' then @item[:aws_architecture] = @text
301
+ when 'imageType' then @item[:aws_image_type] = @text
302
+ when 'kernelId' then @item[:aws_kernel_id] = @text
303
+ when 'ramdiskId' then @item[:aws_ramdisk_id] = @text
304
+ when 'platform' then @item[:aws_platform] = @text
305
+ when 'imageOwnerAlias' then @item[:image_owner_alias] = @text
306
+ when 'name' then @item[:name] = @text
307
+ when 'description' then @item[:description] = @text
308
+ when 'rootDeviceType' then @item[:root_device_type] = @text
309
+ when 'rootDeviceName' then @item[:root_device_name] = @text
310
+ when 'imageClass' then @item[:image_class] = @text
311
+ else
312
+ case full_tag_name
313
+ when %r{/stateReason/code$} then @item[:state_reason_code] = @text.to_i
314
+ when %r{/stateReason/message$} then @item[:state_reason_message] = @text
315
+ when %r{/blockDeviceMapping/item} # no trailing $
316
+ case name
317
+ when 'deviceName' then @block_device_mapping[:device_name] = @text
318
+ when 'virtualName' then @block_device_mapping[:virtual_name] = @text
319
+ when 'volumeSize' then @block_device_mapping[:ebs_volume_size] = @text.to_i
320
+ when 'snapshotId' then @block_device_mapping[:ebs_snapshot_id] = @text
321
+ when 'deleteOnTermination' then @block_device_mapping[:ebs_delete_on_termination] = @text == 'true' ? true : false
322
+ when 'item' then @item[:block_device_mappings] << @block_device_mapping
323
+ end
324
+ when %r{/imagesSet/item$} then @result << @item
325
+ end
326
+ end
327
+ end
328
+ def reset
329
+ @result = []
330
+ end
331
+ end
332
+
333
+ class QEc2RegisterImageParser < RightAWSParser #:nodoc:
334
+ def tagend(name)
335
+ @result = @text if name == 'imageId'
336
+ end
337
+ end
338
+
339
+ #-----------------------------------------------------------------
340
+ # PARSERS: Image Attribute
341
+ #-----------------------------------------------------------------
342
+
343
+ class QEc2DescribeImageAttributeParser < RightAWSParser #:nodoc:
344
+ def tagstart(name, attributes)
345
+ case name
346
+ when 'launchPermission'
347
+ @result[:groups] = []
348
+ @result[:users] = []
349
+ when 'productCodes'
350
+ @result[:aws_product_codes] = []
351
+ end
352
+ end
353
+ def tagend(name)
354
+ # right now only 'launchPermission' is supported by Amazon.
355
+ # But nobody know what will they xml later as attribute. That is why we
356
+ # check for 'group' and 'userId' inside of 'launchPermission/item'
357
+ case name
358
+ when 'imageId' then @result[:aws_id] = @text
359
+ when 'group' then @result[:groups] << @text if @xmlpath == 'DescribeImageAttributeResponse/launchPermission/item'
360
+ when 'userId' then @result[:users] << @text if @xmlpath == 'DescribeImageAttributeResponse/launchPermission/item'
361
+ when 'productCode' then @result[:aws_product_codes] << @text
362
+ when 'kernel' then @result[:aws_kernel] = @text
363
+ when 'ramdisk' then @result[:aws_ramdisk] = @text
364
+ end
365
+ end
366
+ def reset
367
+ @result = {}
368
+ end
369
+ end
370
+
371
+ end
372
+
373
+ end
@@ -0,0 +1,760 @@
1
+ #
2
+ # Copyright (c) 2009 RightScale Inc
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a 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,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #
23
+
24
+ module RightAws
25
+
26
+ class Ec2
27
+
28
+ #-----------------------------------------------------------------
29
+ # Instances
30
+ #-----------------------------------------------------------------
31
+
32
+ def get_desc_instances(instances) # :nodoc:
33
+ result = []
34
+ instances.each do |reservation|
35
+ reservation[:instances_set].each do |instance|
36
+ # Parse and remove timestamp from the reason string. The timestamp is of
37
+ # the request, not when EC2 took action, thus confusing & useless...
38
+ instance[:aws_reason] = instance[:aws_reason].sub(/\(\d[^)]*GMT\) */, '')
39
+ instance[:aws_owner] = reservation[:aws_owner]
40
+ instance[:aws_reservation_id] = reservation[:aws_reservation_id]
41
+ instance[:aws_groups] = reservation[:aws_groups]
42
+ result << instance
43
+ end
44
+ end
45
+ result
46
+ rescue Exception
47
+ on_exception
48
+ end
49
+
50
+ # Retrieve information about EC2 instances. If +list+ is omitted then returns the
51
+ # list of all instances.
52
+ #
53
+ # ec2.describe_instances #=>
54
+ # [{:private_ip_address=>"10.240.7.99",
55
+ # :aws_image_id=>"ami-c2a3f5d4",
56
+ # :ip_address=>"174.129.134.109",
57
+ # :dns_name=>"ec2-174-129-134-109.compute-1.amazonaws.com",
58
+ # :aws_instance_type=>"m1.small",
59
+ # :aws_owner=>"826693181925",
60
+ # :root_device_name=>"/dev/sda1",
61
+ # :instance_class=>"elastic",
62
+ # :aws_state=>"running",
63
+ # :private_dns_name=>"domU-12-31-39-04-00-95.compute-1.internal",
64
+ # :aws_reason=>"",
65
+ # :aws_launch_time=>"2009-11-18T14:03:25.000Z",
66
+ # :aws_reservation_id=>"r-54d38542",
67
+ # :aws_state_code=>16,
68
+ # :ami_launch_index=>"0",
69
+ # :aws_availability_zone=>"us-east-1a",
70
+ # :aws_groups=>["default"],
71
+ # :monitoring_state=>"disabled",
72
+ # :aws_product_codes=>[],
73
+ # :ssh_key_name=>"",
74
+ # :block_device_mappings=>
75
+ # [{:ebs_status=>"attached",
76
+ # :ebs_delete_on_termination=>true,
77
+ # :ebs_attach_time=>"2009-11-18T14:03:34.000Z",
78
+ # :device_name=>"/dev/sda1",
79
+ # :ebs_volume_id=>"vol-e600f98f"},
80
+ # {:ebs_status=>"attached",
81
+ # :ebs_delete_on_termination=>true,
82
+ # :ebs_attach_time=>"2009-11-18T14:03:34.000Z",
83
+ # :device_name=>"/dev/sdk",
84
+ # :ebs_volume_id=>"vol-f900f990"}],
85
+ # :aws_instance_id=>"i-8ce84ae4"} , ... ]
86
+ #
87
+ def describe_instances(list=[])
88
+ link = generate_request("DescribeInstances", amazonize_list('InstanceId',list.to_a))
89
+ request_cache_or_info(:describe_instances, link, QEc2DescribeInstancesParser, @@bench, list.blank?) do |parser|
90
+ get_desc_instances(parser.result)
91
+ end
92
+ rescue Exception
93
+ on_exception
94
+ end
95
+
96
+ # Return the product code attached to instance or +nil+ otherwise.
97
+ #
98
+ # ec2.confirm_product_instance('ami-e444444d','12345678') #=> nil
99
+ # ec2.confirm_product_instance('ami-e444444d','00001111') #=> "000000000888"
100
+ #
101
+ def confirm_product_instance(instance, product_code)
102
+ link = generate_request("ConfirmProductInstance", { 'ProductCode' => product_code,
103
+ 'InstanceId' => instance })
104
+ request_info(link, QEc2ConfirmProductInstanceParser.new(:logger => @logger))
105
+ end
106
+
107
+ # Launch new EC2 instances. Returns a list of launched instances or an exception.
108
+ #
109
+ # ec2.run_instances('ami-e444444d',1,1,['my_awesome_group'],'my_awesome_key', 'Woohoo!!!', 'public') #=>
110
+ # [{:aws_image_id => "ami-e444444d",
111
+ # :aws_reason => "",
112
+ # :aws_state_code => "0",
113
+ # :aws_owner => "000000000888",
114
+ # :aws_instance_id => "i-123f1234",
115
+ # :aws_reservation_id => "r-aabbccdd",
116
+ # :aws_state => "pending",
117
+ # :dns_name => "",
118
+ # :ssh_key_name => "my_awesome_key",
119
+ # :aws_groups => ["my_awesome_group"],
120
+ # :private_dns_name => "",
121
+ # :aws_instance_type => "m1.small",
122
+ # :aws_launch_time => "2008-1-1T00:00:00.000Z"
123
+ # :aws_ramdisk_id => "ari-8605e0ef"
124
+ # :aws_kernel_id => "aki-9905e0f0",
125
+ # :ami_launch_index => "0",
126
+ # :aws_availability_zone => "us-east-1b"
127
+ # }]
128
+ #
129
+ def run_instances(image_id, min_count, max_count, group_ids, key_name, user_data='',
130
+ addressing_type = nil, instance_type = nil,
131
+ kernel_id = nil, ramdisk_id = nil, availability_zone = nil,
132
+ monitoring_enabled = nil, subnet_id = nil, disable_api_termination = nil,
133
+ instance_initiated_shutdown_behavior = nil, block_device_mappings = nil)
134
+ launch_instances(image_id, { :min_count => min_count,
135
+ :max_count => max_count,
136
+ :user_data => user_data,
137
+ :group_ids => group_ids,
138
+ :key_name => key_name,
139
+ :instance_type => instance_type,
140
+ :addressing_type => addressing_type,
141
+ :kernel_id => kernel_id,
142
+ :ramdisk_id => ramdisk_id,
143
+ :availability_zone => availability_zone,
144
+ :monitoring_enabled => monitoring_enabled,
145
+ :subnet_id => subnet_id,
146
+ :disable_api_termination => disable_api_termination,
147
+ :instance_initiated_shutdown_behavior => instance_initiated_shutdown_behavior,
148
+ :block_device_mappings => block_device_mappings
149
+ })
150
+ end
151
+
152
+ # Launch new EC2 instances.
153
+ # Options: :image_id, :addressing_type, :min_count, max_count, :key_name, :kernel_id, :ramdisk_id,
154
+ # :availability_zone, :monitoring_enabled, :subnet_id, :disable_api_termination, :instance_initiated_shutdown_behavior,
155
+ # :block_device_mappings
156
+ #
157
+ # Returns a list of launched instances or an exception.
158
+ #
159
+ # ec2.launch_instances( 'ami-c2a3f5d4',
160
+ # :min_count => 1,
161
+ # :group_ids => 'default',
162
+ # :user_data => 'Ohoho!',
163
+ # :availability_zone => "us-east-1a",
164
+ # :disable_api_termination => true,
165
+ # :instance_initiated_shutdown_behavior => 'terminate',
166
+ # :block_device_mappings => [ {:ebs_snapshot_id=>"snap-7360871a",
167
+ # :ebs_delete_on_termination=>true,
168
+ # :device_name => "/dev/sdk",
169
+ # :virtual_name => "mystorage"} ] ) #=>
170
+ # [{:aws_image_id=>"ami-c2a3f5d4",
171
+ # :dns_name=>"",
172
+ # :aws_instance_type=>"m1.small",
173
+ # :aws_owner=>"826693181925",
174
+ # :root_device_name=>"/dev/sda1",
175
+ # :instance_class=>"elastic",
176
+ # :state_reason_code=>0,
177
+ # :aws_state=>"pending",
178
+ # :private_dns_name=>"",
179
+ # :aws_reason=>"",
180
+ # :aws_launch_time=>"2009-11-18T14:03:25.000Z",
181
+ # :aws_reservation_id=>"r-54d38542",
182
+ # :state_reason_message=>"pending",
183
+ # :aws_state_code=>0,
184
+ # :ami_launch_index=>"0",
185
+ # :aws_availability_zone=>"us-east-1a",
186
+ # :aws_groups=>["default"],
187
+ # :monitoring_state=>"disabled",
188
+ # :aws_product_codes=>[],
189
+ # :ssh_key_name=>"",
190
+ # :aws_instance_id=>"i-8ce84ae4"}]
191
+ #
192
+ def launch_instances(image_id, options={})
193
+ @logger.info("Launching instance of image #{image_id} for #{@aws_access_key_id}, " +
194
+ "key: #{options[:key_name]}, groups: #{(options[:group_ids]).to_a.join(',')}")
195
+ options[:image_id] = image_id
196
+ options[:min_count] ||= 1
197
+ options[:max_count] ||= options[:min_count]
198
+ params = prepare_instance_launch_params(options)
199
+ link = generate_request("RunInstances", params)
200
+ instances = request_info(link, QEc2DescribeInstancesParser.new(:logger => @logger))
201
+ get_desc_instances(instances)
202
+ rescue Exception
203
+ on_exception
204
+ end
205
+
206
+ =begin
207
+ # TODO: API does not support this call yet
208
+ def create_instance(options={})
209
+ @logger.info("Creating instance #{@aws_access_key_id}, " +
210
+ "key: #{options[:key_name]}, groups: #{(options[:group_ids]).to_a.join(',')}")
211
+ params = prepare_instance_launch_params(options)
212
+ link = generate_request("CreateInstance", params)
213
+ instances = request_info(link, QEc2DescribeInstancesParser.new(:logger => @logger))
214
+ get_desc_instances(instances).first
215
+ rescue Exception
216
+ on_exception
217
+ end
218
+ =end
219
+
220
+ def prepare_instance_launch_params(options={}) # :nodoc:
221
+ params = amazonize_list('SecurityGroup', options[:group_ids].to_a)
222
+ params['InstanceType'] = options[:instance_type] || DEFAULT_INSTANCE_TYPE
223
+ params['ImageId'] = options[:image_id] unless options[:image_id].blank?
224
+ params['AddressingType'] = options[:addressing_type] unless options[:addressing_type].blank?
225
+ params['MinCount'] = options[:min_count] unless options[:min_count].blank?
226
+ params['MaxCount'] = options[:max_count] unless options[:max_count].blank?
227
+ params['KeyName'] = options[:key_name] unless options[:key_name].blank?
228
+ params['KernelId'] = options[:kernel_id] unless options[:kernel_id].blank?
229
+ params['RamdiskId'] = options[:ramdisk_id] unless options[:ramdisk_id].blank?
230
+ params['Placement.AvailabilityZone'] = options[:availability_zone] unless options[:availability_zone].blank?
231
+ params['Monitoring.Enabled'] = options[:monitoring_enabled].to_s if options[:monitoring_enabled]
232
+ params['SubnetId'] = options[:subnet_id] unless options[:subnet_id].blank?
233
+ params['AdditionalInfo'] = options[:additional_info] unless options[:additional_info].blank?
234
+ params['DisableApiTermination'] = options[:disable_api_termination].to_s unless options[:disable_api_termination].nil?
235
+ params['InstanceInitiatedShutdownBehavior'] = options[:instance_initiated_shutdown_behavior] unless options[:instance_initiated_shutdown_behavior].blank?
236
+ # params['VolumeId'] = options[:volume_id] unless options[:volume_id].blank?
237
+ # params['RootDeviceName'] = options[:root_device_name] unless options[:root_device_name].blank?
238
+ # params['RootDeviceType'] = options[:root_device_type] unless options[:root_device_type].blank?
239
+ params.merge!(amazonize_block_device_mappings(options[:block_device_mappings]))
240
+ unless options[:user_data].blank?
241
+ options[:user_data].strip!
242
+ # Do not use CGI::escape(encode64(...)) as it is done in Amazons EC2 library.
243
+ # Amazon 169.254.169.254 does not like escaped symbols!
244
+ # And it doesn't like "\n" inside of encoded string! Grrr....
245
+ # Otherwise, some of UserData symbols will be lost...
246
+ params['UserData'] = Base64.encode64(options[:user_data]).delete("\n") unless options[:user_data].blank?
247
+ end
248
+ params
249
+ end
250
+
251
+ # Start instances.
252
+ #
253
+ # ec2.start_instances("i-36e84a5e") #=>
254
+ # [{:aws_prev_state_name=>"stopped",
255
+ # :aws_instance_id=>"i-36e84a5e",
256
+ # :aws_current_state_code=>16,
257
+ # :aws_current_state_name=>"running",
258
+ # :aws_prev_state_code=>80}]
259
+ #
260
+ def start_instances(*instance_aws_ids)
261
+ instance_aws_ids = instance_aws_ids.flatten
262
+ link = generate_request("StartInstances", amazonize_list('InstanceId', instance_aws_ids))
263
+ request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
264
+ end
265
+
266
+ # Stop instances.
267
+ #
268
+ # ec2.stop_instances("i-36e84a5e") #=>
269
+ # [{:aws_prev_state_code=>16,
270
+ # :aws_prev_state_name=>"running",
271
+ # :aws_instance_id=>"i-36e84a5e",
272
+ # :aws_current_state_code=>64,
273
+ # :aws_current_state_name=>"stopping"}]
274
+ #
275
+ def stop_instances(*instance_aws_ids)
276
+ instance_aws_ids = instance_aws_ids.flatten
277
+ link = generate_request("StopInstances", amazonize_list('InstanceId', instance_aws_ids))
278
+ request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
279
+ end
280
+
281
+ # Terminates EC2 instances. Returns a list of termination params or an exception.
282
+ #
283
+ # ec2.terminate_instances(['i-cceb49a4']) #=>
284
+ # [{:aws_instance_id=>"i-cceb49a4",
285
+ # :aws_current_state_code=>32,
286
+ # :aws_current_state_name=>"shutting-down",
287
+ # :aws_prev_state_code=>16,
288
+ # :aws_prev_state_name=>"running"}]
289
+ #
290
+ def terminate_instances(*instance_aws_ids)
291
+ instance_aws_ids = instance_aws_ids.flatten
292
+ link = generate_request("TerminateInstances", amazonize_list('InstanceId', instance_aws_ids))
293
+ request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
294
+ rescue Exception
295
+ on_exception
296
+ end
297
+
298
+ # Retreive EC2 instance OS logs. Returns a hash of data or an exception.
299
+ #
300
+ # ec2.get_console_output('i-f222222d') =>
301
+ # {:aws_instance_id => 'i-f222222d',
302
+ # :aws_timestamp => "2007-05-23T14:36:07.000-07:00",
303
+ # :timestamp => Wed May 23 21:36:07 UTC 2007, # Time instance
304
+ # :aws_output => "Linux version 2.6.16-xenU (builder@patchbat.amazonsa) (gcc version 4.0.1 20050727 ..."
305
+ def get_console_output(instance_id)
306
+ link = generate_request("GetConsoleOutput", { 'InstanceId.1' => instance_id })
307
+ request_info(link, QEc2GetConsoleOutputParser.new(:logger => @logger))
308
+ rescue Exception
309
+ on_exception
310
+ end
311
+
312
+ # Reboot an EC2 instance. Returns +true+ or an exception.
313
+ #
314
+ # ec2.reboot_instances(['i-f222222d','i-f222222e']) #=> true
315
+ #
316
+ def reboot_instances(list)
317
+ link = generate_request("RebootInstances", amazonize_list('InstanceId', list.to_a))
318
+ request_info(link, RightBoolResponseParser.new(:logger => @logger))
319
+ rescue Exception
320
+ on_exception
321
+ end
322
+
323
+ INSTANCE_ATTRIBUTE_MAPPING = {
324
+ "instance_type" => "instanceType",
325
+ "kernel" => "kernel",
326
+ "ramdisk" => "ramdisk",
327
+ "user_data" => "userData",
328
+ "disable_api_termination" => "disableApiTermination",
329
+ "instance_initiated_shutdown_behavior" => "instanceInitiatedShutdownBehavior",
330
+ "root_device_name" => "rootDeviceName",
331
+ "block_device_mapping" => "blockDeviceMapping"
332
+ }
333
+
334
+ # Describe instance attribute.
335
+ # Attributes: :instance_type, :kernel, :ramdisk, :user_data, :disable_api_termination, :instance_initiated_shutdown_behavior, :root_device_name, :block_device_mapping
336
+ #
337
+ # ec2.describe_instance_attribute(instance, "BlockDeviceMapping") #=>
338
+ # [{:ebs_delete_on_termination=>true,
339
+ # :ebs_volume_id=>"vol-683dc401",
340
+ # :device_name=>"/dev/sda1"}]
341
+ #
342
+ # ec2.describe_instance_attribute(instance, "InstanceType") #=> "m1.small"
343
+ #
344
+ # ec2.describe_instance_attribute(instance, "InstanceInitiatedShutdownBehavior") #=> "stop"
345
+ #
346
+ def describe_instance_attribute(instance_id, attribute)
347
+ attribute = INSTANCE_ATTRIBUTE_MAPPING[attribute.to_s] || attribute.to_s
348
+ link = generate_request('DescribeInstanceAttribute',
349
+ 'InstanceId' => instance_id,
350
+ 'Attribute' => attribute)
351
+ value = request_info(link, QEc2DescribeInstanceAttributeParser.new(:logger => @logger))
352
+ case attribute
353
+ when "userData"
354
+ Base64.decode64(value)
355
+ else
356
+ value
357
+ end
358
+ rescue Exception
359
+ on_exception
360
+ end
361
+
362
+ # Describe instance attribute.
363
+ # Attributes: :kernel, :ramdisk
364
+ #
365
+ # ec2.reset_instance_attribute(instance, :kernel) #=> true
366
+ #
367
+ def reset_instance_attribute(instance_id, attribute)
368
+ attribute = INSTANCE_ATTRIBUTE_MAPPING[attribute.to_s] || attribute.to_s
369
+ link = generate_request('ResetInstanceAttribute',
370
+ 'InstanceId' => instance_id,
371
+ 'Attribute' => attribute )
372
+ request_info(link, RightBoolResponseParser.new(:logger => @logger))
373
+ rescue Exception
374
+ on_exception
375
+ end
376
+
377
+ # Modify instance attribute.
378
+ # Attributes: :instance_type, :kernel, :ramdisk, :user_data, :disable_api_termination, :instance_initiated_shutdown_behavior, :root_device_name, :block_device_mapping
379
+ #
380
+ # ec2.modify_instance_attribute(instance, :instance_initiated_shutdown_behavior, "stop") #=> true
381
+ #
382
+ def modify_instance_attribute(instance_id, attribute, value)
383
+ attribute = INSTANCE_ATTRIBUTE_MAPPING[attribute.to_s] || attribute.to_s
384
+ params = { 'InstanceId' => instance_id,
385
+ 'Attribute' => attribute }
386
+ case attribute
387
+ when "blockDeviceMapping"
388
+ params.merge!(amazonize_block_device_mappings(value))
389
+ when "userData"
390
+ params['Value'] = Base64.encode64(value).delete("\n")
391
+ else
392
+ params['Value'] = value
393
+ end
394
+ link = generate_request('ModifyInstanceAttribute', params)
395
+ request_info(link, RightBoolResponseParser.new(:logger => @logger))
396
+ rescue Exception
397
+ on_exception
398
+ end
399
+
400
+ #-----------------------------------------------------------------
401
+ # Instances: Windows addons
402
+ #-----------------------------------------------------------------
403
+
404
+ # Get initial Windows Server setup password from an instance console output.
405
+ #
406
+ # my_awesome_key = ec2.create_key_pair('my_awesome_key') #=>
407
+ # {:aws_key_name => "my_awesome_key",
408
+ # :aws_fingerprint => "01:02:03:f4:25:e6:97:e8:9b:02:1a:26:32:4e:58:6b:7a:8c:9f:03",
409
+ # :aws_material => "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAK...Q8MDrCbuQ=\n-----END RSA PRIVATE KEY-----"}
410
+ #
411
+ # my_awesome_instance = ec2.run_instances('ami-a000000a',1,1,['my_awesome_group'],'my_awesome_key', 'WindowsInstance!!!') #=>
412
+ # [{:aws_image_id => "ami-a000000a",
413
+ # :aws_instance_id => "i-12345678",
414
+ # ...
415
+ # :aws_availability_zone => "us-east-1b"
416
+ # }]
417
+ #
418
+ # # wait until instance enters 'operational' state and get it's initial password
419
+ #
420
+ # puts ec2.get_initial_password(my_awesome_instance[:aws_instance_id], my_awesome_key[:aws_material]) #=> "MhjWcgZuY6"
421
+ #
422
+ def get_initial_password(instance_id, private_key)
423
+ console_output = get_console_output(instance_id)
424
+ crypted_password = console_output[:aws_output][%r{<Password>(.+)</Password>}m] && $1
425
+ unless crypted_password
426
+ raise AwsError.new("Initial password was not found in console output for #{instance_id}")
427
+ else
428
+ OpenSSL::PKey::RSA.new(private_key).private_decrypt(Base64.decode64(crypted_password))
429
+ end
430
+ rescue Exception
431
+ on_exception
432
+ end
433
+
434
+ # Bundle a Windows image.
435
+ # Internally, it queues the bundling task and shuts down the instance.
436
+ # It then takes a snapshot of the Windows volume bundles it, and uploads it to
437
+ # S3. After bundling completes, Rightaws::Ec2#register_image may be used to
438
+ # register the new Windows AMI for subsequent launches.
439
+ #
440
+ # ec2.bundle_instance('i-e3e24e8a', 'my-awesome-bucket', 'my-win-image-1') #=>
441
+ # [{:aws_update_time => "2008-10-16T13:58:25.000Z",
442
+ # :s3_bucket => "kd-win-1",
443
+ # :s3_prefix => "win2pr",
444
+ # :aws_state => "pending",
445
+ # :aws_id => "bun-26a7424f",
446
+ # :aws_instance_id => "i-878a25ee",
447
+ # :aws_start_time => "2008-10-16T13:58:02.000Z"}]
448
+ #
449
+ def bundle_instance(instance_id, s3_bucket, s3_prefix,
450
+ s3_owner_aws_access_key_id=nil, s3_owner_aws_secret_access_key=nil,
451
+ s3_expires = S3Interface::DEFAULT_EXPIRES_AFTER,
452
+ s3_upload_policy='ec2-bundle-read')
453
+ # S3 access and signatures
454
+ s3_owner_aws_access_key_id ||= @aws_access_key_id
455
+ s3_owner_aws_secret_access_key ||= @aws_secret_access_key
456
+ s3_expires = Time.now.utc + s3_expires if s3_expires.is_a?(Fixnum) && (s3_expires < S3Interface::ONE_YEAR_IN_SECONDS)
457
+ # policy
458
+ policy = { 'expiration' => s3_expires.strftime('%Y-%m-%dT%H:%M:%SZ'),
459
+ 'conditions' => [ { 'bucket' => s3_bucket },
460
+ { 'acl' => s3_upload_policy },
461
+ [ 'starts-with', '$key', s3_prefix ] ] }.to_json
462
+ policy64 = Base64.encode64(policy).gsub("\n","")
463
+ signed_policy64 = AwsUtils.sign(s3_owner_aws_secret_access_key, policy64)
464
+ # fill request params
465
+ params = { 'InstanceId' => instance_id,
466
+ 'Storage.S3.AWSAccessKeyId' => s3_owner_aws_access_key_id,
467
+ 'Storage.S3.UploadPolicy' => policy64,
468
+ 'Storage.S3.UploadPolicySignature' => signed_policy64,
469
+ 'Storage.S3.Bucket' => s3_bucket,
470
+ 'Storage.S3.Prefix' => s3_prefix,
471
+ }
472
+ link = generate_request("BundleInstance", params)
473
+ request_info(link, QEc2BundleInstanceParser.new)
474
+ rescue Exception
475
+ on_exception
476
+ end
477
+
478
+ # Describe the status of the Windows AMI bundlings.
479
+ # If +list+ is omitted the returns the whole list of tasks.
480
+ #
481
+ # ec2.describe_bundle_tasks(['bun-4fa74226']) #=>
482
+ # [{:s3_bucket => "my-awesome-bucket"
483
+ # :aws_id => "bun-0fa70206",
484
+ # :s3_prefix => "win1pr",
485
+ # :aws_start_time => "2008-10-14T16:27:57.000Z",
486
+ # :aws_update_time => "2008-10-14T16:37:10.000Z",
487
+ # :aws_error_code => "Client.S3Error",
488
+ # :aws_error_message =>
489
+ # "AccessDenied(403)- Invalid according to Policy: Policy Condition failed: [\"eq\", \"$acl\", \"aws-exec-read\"]",
490
+ # :aws_state => "failed",
491
+ # :aws_instance_id => "i-e3e24e8a"}]
492
+ #
493
+ def describe_bundle_tasks(list=[])
494
+ link = generate_request("DescribeBundleTasks", amazonize_list('BundleId', list.to_a))
495
+ request_info(link, QEc2DescribeBundleTasksParser.new)
496
+ rescue Exception
497
+ on_exception
498
+ end
499
+
500
+ # Cancel an in‐progress or pending bundle task by id.
501
+ #
502
+ # ec2.cancel_bundle_task('bun-73a7421a') #=>
503
+ # [{:s3_bucket => "my-awesome-bucket"
504
+ # :aws_id => "bun-0fa70206",
505
+ # :s3_prefix => "win02",
506
+ # :aws_start_time => "2008-10-14T13:00:29.000Z",
507
+ # :aws_error_message => "User has requested bundling operation cancellation",
508
+ # :aws_state => "failed",
509
+ # :aws_update_time => "2008-10-14T13:01:31.000Z",
510
+ # :aws_error_code => "Client.Cancelled",
511
+ # :aws_instance_id => "i-e3e24e8a"}
512
+ #
513
+ def cancel_bundle_task(bundle_id)
514
+ link = generate_request("CancelBundleTask", { 'BundleId' => bundle_id })
515
+ request_info(link, QEc2BundleInstanceParser.new)
516
+ rescue Exception
517
+ on_exception
518
+ end
519
+
520
+ #-----------------------------------------------------------------
521
+ # Helpers
522
+ #-----------------------------------------------------------------
523
+
524
+ BLOCK_DEVICE_KEY_MAPPING = { # :nodoc:
525
+ :device_name => 'DeviceName',
526
+ :virtual_name => 'VirtualName',
527
+ :no_device => 'NoDevice',
528
+ :ebs_snapshot_id => 'Ebs.SnapshotId',
529
+ :ebs_volume_size => 'Ebs.VolumeSize',
530
+ :ebs_delete_on_termination => 'Ebs.DeleteOnTermination' }
531
+
532
+ def amazonize_block_device_mappings(block_device_mappings) # :nodoc:
533
+ result = {}
534
+ unless block_device_mappings.blank?
535
+ block_device_mappings = [block_device_mappings] unless block_device_mappings.is_a?(Array)
536
+ block_device_mappings.each_with_index do |b, idx|
537
+ BLOCK_DEVICE_KEY_MAPPING.each do |local_name, remote_name|
538
+ value = b[local_name]
539
+ case local_name
540
+ when :no_device then value = value ? '' : nil # allow to pass :no_device as boolean
541
+ end
542
+ result["BlockDeviceMapping.#{idx+1}.#{remote_name}"] = value unless value.nil?
543
+ end
544
+ end
545
+ end
546
+ result
547
+ end
548
+
549
+ #-----------------------------------------------------------------
550
+ # PARSERS: Instances
551
+ #-----------------------------------------------------------------
552
+
553
+ class QEc2DescribeInstancesParser < RightAWSParser #:nodoc:
554
+ def tagstart(name, attributes)
555
+ # DescribeInstances property
556
+ case full_tag_name
557
+ when 'DescribeInstancesResponse/reservationSet/item',
558
+ 'RunInstancesResponse'
559
+ @reservation = { :aws_groups => [],
560
+ :instances_set => [] }
561
+ when %r{instancesSet/item$}
562
+ # the optional params (sometimes are missing and we dont want them to be nil)
563
+ @item = { :aws_reason => '',
564
+ :dns_name => '',
565
+ :private_dns_name => '',
566
+ :ami_launch_index => '',
567
+ :ssh_key_name => '',
568
+ :aws_state => '',
569
+ :aws_product_codes => [] }
570
+ when %r{blockDeviceMapping/item$}
571
+ @item[:block_device_mappings] ||= []
572
+ @block_device_mapping = {}
573
+ end
574
+ end
575
+ def tagend(name)
576
+ case name
577
+ when 'reservationId' then @reservation[:aws_reservation_id] = @text
578
+ when 'ownerId' then @reservation[:aws_owner] = @text
579
+ when 'groupId' then @reservation[:aws_groups] << @text
580
+ when 'instanceId' then @item[:aws_instance_id] = @text
581
+ when 'imageId' then @item[:aws_image_id] = @text
582
+ when 'privateDnsName' then @item[:private_dns_name] = @text
583
+ when 'dnsName' then @item[:dns_name] = @text
584
+ when 'reason' then @item[:aws_reason] = @text
585
+ when 'keyName' then @item[:ssh_key_name] = @text
586
+ when 'amiLaunchIndex' then @item[:ami_launch_index] = @text
587
+ when 'productCode' then @item[:aws_product_codes] << @text
588
+ when 'instanceType' then @item[:aws_instance_type] = @text
589
+ when 'launchTime' then @item[:aws_launch_time] = @text
590
+ when 'availabilityZone' then @item[:aws_availability_zone] = @text
591
+ when 'kernelId' then @item[:aws_kernel_id] = @text
592
+ when 'ramdiskId' then @item[:aws_ramdisk_id] = @text
593
+ when 'platform' then @item[:aws_platform] = @text
594
+ when 'subnetId' then @item[:subnet_id] = @text
595
+ when 'vpcId' then @item[:vpc_id] = @text
596
+ when 'privateIpAddress' then @item[:private_ip_address] = @text
597
+ when 'ipAddress' then @item[:ip_address] = @text
598
+ when 'architecture' then @item[:architecture] = @text
599
+ when 'rootDeviceType' then @item[:root_device_type] = @text
600
+ when 'rootDeviceName' then @item[:root_device_name] = @text
601
+ when 'instanceClass' then @item[:instance_class] = @text
602
+ else
603
+ case full_tag_name
604
+ when %r{/stateReason/code$} then @item[:state_reason_code] = @text.to_i
605
+ when %r{/stateReason/message$} then @item[:state_reason_message] = @text
606
+ when %r{/instanceState/code$} then @item[:aws_state_code] = @text.to_i
607
+ when %r{/instanceState/name$} then @item[:aws_state] = @text
608
+ when %r{/monitoring/state$} then @item[:monitoring_state] = @text
609
+ when %r{/blockDeviceMapping/item} # no trailing $
610
+ case name
611
+ when 'deviceName' then @block_device_mapping[:device_name] = @text
612
+ when 'virtualName' then @block_device_mapping[:virtual_name] = @text
613
+ when 'volumeId' then @block_device_mapping[:ebs_volume_id] = @text
614
+ when 'status' then @block_device_mapping[:ebs_status] = @text
615
+ when 'attachTime' then @block_device_mapping[:ebs_attach_time] = @text
616
+ when 'deleteOnTermination' then @block_device_mapping[:ebs_delete_on_termination] = @text == 'true' ? true : false
617
+ when 'item' then @item[:block_device_mappings] << @block_device_mapping
618
+ end
619
+ when %r{/instancesSet/item$} then @reservation[:instances_set] << @item
620
+ when 'DescribeInstancesResponse/reservationSet/item',
621
+ 'RunInstancesResponse'
622
+ @result << @reservation
623
+ end
624
+ end
625
+ end
626
+ def reset
627
+ @result = []
628
+ end
629
+ end
630
+
631
+ class QEc2ConfirmProductInstanceParser < RightAWSParser #:nodoc:
632
+ def tagend(name)
633
+ @result = @text if name == 'ownerId'
634
+ end
635
+ end
636
+
637
+ class QEc2TerminateInstancesParser < RightAWSParser #:nodoc:
638
+ def tagstart(name, attributes)
639
+ @instance = {} if name == 'item'
640
+ end
641
+ def tagend(name)
642
+ case full_tag_name
643
+ when %r{/instanceId$} then @instance[:aws_instance_id] = @text
644
+ when %r{/currentState/code$} then @instance[:aws_current_state_code] = @text.to_i
645
+ when %r{/currentState/name$} then @instance[:aws_current_state_name] = @text
646
+ when %r{/previousState/code$} then @instance[:aws_prev_state_code] = @text.to_i
647
+ when %r{/previousState/name$} then @instance[:aws_prev_state_name] = @text
648
+ when %r{/item$} then @result << @instance
649
+ end
650
+ end
651
+ def reset
652
+ @result = []
653
+ end
654
+ end
655
+
656
+ class QEc2DescribeInstanceAttributeParser < RightAWSParser #:nodoc:
657
+ def tagstart(name, attributes)
658
+ case full_tag_name
659
+ when %r{blockDeviceMapping$} then @result = []
660
+ when %r{blockDeviceMapping/item$} then @block_device_mapping = {}
661
+ end
662
+ end
663
+ def tagend(name)
664
+ case full_tag_name
665
+ when %r{/instanceType/value$} then @result = @text
666
+ when %r{/kernel$} then @result = @text
667
+ when %r{/ramdisk$} then @result = @text
668
+ when %r{/userData$} then @result = @text
669
+ when %r{/rootDeviceName/value$} then @result = @text
670
+ when %r{/disableApiTermination/value} then @result = @text == 'true' ? true : false
671
+ when %r{/instanceInitiatedShutdownBehavior/value$} then @result = @text
672
+ when %r{/blockDeviceMapping/item} # no trailing $
673
+ case name
674
+ when 'deviceName' then @block_device_mapping[:device_name] = @text
675
+ when 'virtualName' then @block_device_mapping[:virtual_name] = @text
676
+ when 'noDevice' then @block_device_mapping[:no_device] = @text
677
+ when 'volumeId' then @block_device_mapping[:ebs_volume_id] = @text
678
+ when 'status' then @block_device_mapping[:ebs_status] = @text
679
+ when 'attachTime' then @block_device_mapping[:ebs_attach_time] = @text
680
+ when 'deleteOnTermination' then @block_device_mapping[:ebs_delete_on_termination] = @text == 'true' ? true : false
681
+ when 'item' then @result << @block_device_mapping
682
+ end
683
+ end
684
+ end
685
+ def reset
686
+ @result = nil
687
+ end
688
+ end
689
+
690
+ #-----------------------------------------------------------------
691
+ # PARSERS: Console
692
+ #-----------------------------------------------------------------
693
+
694
+ class QEc2GetConsoleOutputParser < RightAWSParser #:nodoc:
695
+ def tagend(name)
696
+ case name
697
+ when 'instanceId' then @result[:aws_instance_id] = @text
698
+ when 'timestamp' then @result[:aws_timestamp] = @text
699
+ @result[:timestamp] = (Time.parse(@text)).utc
700
+ when 'output' then @result[:aws_output] = Base64.decode64(@text)
701
+ end
702
+ end
703
+ def reset
704
+ @result = {}
705
+ end
706
+ end
707
+
708
+ #-----------------------------------------------------------------
709
+ # Instances: Windows related part
710
+ #-----------------------------------------------------------------
711
+
712
+ class QEc2DescribeBundleTasksParser < RightAWSParser #:nodoc:
713
+ def tagstart(name, attributes)
714
+ @bundle = {} if name == 'item'
715
+ end
716
+ def tagend(name)
717
+ case name
718
+ # when 'requestId' then @bundle[:request_id] = @text
719
+ when 'instanceId' then @bundle[:aws_instance_id] = @text
720
+ when 'bundleId' then @bundle[:aws_id] = @text
721
+ when 'bucket' then @bundle[:s3_bucket] = @text
722
+ when 'prefix' then @bundle[:s3_prefix] = @text
723
+ when 'startTime' then @bundle[:aws_start_time] = @text
724
+ when 'updateTime' then @bundle[:aws_update_time] = @text
725
+ when 'state' then @bundle[:aws_state] = @text
726
+ when 'progress' then @bundle[:aws_progress] = @text
727
+ when 'code' then @bundle[:aws_error_code] = @text
728
+ when 'message' then @bundle[:aws_error_message] = @text
729
+ when 'item' then @result << @bundle
730
+ end
731
+ end
732
+ def reset
733
+ @result = []
734
+ end
735
+ end
736
+
737
+ class QEc2BundleInstanceParser < RightAWSParser #:nodoc:
738
+ def tagend(name)
739
+ case name
740
+ # when 'requestId' then @result[:request_id] = @text
741
+ when 'instanceId' then @result[:aws_instance_id] = @text
742
+ when 'bundleId' then @result[:aws_id] = @text
743
+ when 'bucket' then @result[:s3_bucket] = @text
744
+ when 'prefix' then @result[:s3_prefix] = @text
745
+ when 'startTime' then @result[:aws_start_time] = @text
746
+ when 'updateTime' then @result[:aws_update_time] = @text
747
+ when 'state' then @result[:aws_state] = @text
748
+ when 'progress' then @result[:aws_progress] = @text
749
+ when 'code' then @result[:aws_error_code] = @text
750
+ when 'message' then @result[:aws_error_message] = @text
751
+ end
752
+ end
753
+ def reset
754
+ @result = {}
755
+ end
756
+ end
757
+
758
+ end
759
+
760
+ end