Berlin Berlin - 1 year ago 52
Ruby Question

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

The result of

p snapshot.tags

[#<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
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

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


Answer Source


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 = 'us-east-1')

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

Output looks like

snap-01234567 : 2016-09-30