Berlin Berlin - 2 months ago 11
Ruby Question

ruby aws sdk v2 how to get the value of snapshot tag

The result of

p snapshot.tags
is:

[#<struct Aws::EC2::Types::Tag key="snapshot_expire", value="2016-09-23 08:30:12 +0000">]


How do I get only the value of Tag Key
snapshot_expire
without the hour:sec:min (2016-09-23) ?

This is my code:

resp = ec2.describe_snapshots(owner_ids:['1234']) #.each do |snapshot|
resp.snapshots.each do |snapshot|
p snapshot.snapshot_id
p snapshot.tags
end


I know that the regular aws cli tool has this option.

Thanks!

Answer

Reference: http://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Client.html#describe_snapshots-instance_method

The 'snapshots' are returned as objects. You can get the specific snapshot data from the object using methods; see the documentation above. The snapshot ID is available by calling snapshot.snapshot_id. Tags are snapshot.tags.

require 'aws-sdk'
require 'date'
ec2 = Aws::EC2::Client.new(region: 'us-east-1')

snapshot_response = ec2.describe_snapshots(owner_ids:['xxx'])
snapshot_response.snapshots.each do |snapshot|
  tagkeyexpire = snapshot.tags.select{|tag| tag.key == 'snapshot_expire'}
  snapid = snapshot.snapshot_id
  expiredate = Date.parse(tagkeyexpire[0].value) unless tagkeyexpire == []
  puts "#{snapid} : #{expiredate}"
end

Output looks like

snap-01234567 : 2016-09-30