How to list all tags of an AWS resource using Ruby SDK
1 min readFeb 3, 2020
In my case, I get a resource ID of a subnet, which looks like:
subnet-009abbace367f2c03
And, I want to get all the tags of this subnet.
To do so:
# Aws SDK 2@ec2 ||= Aws::EC2::Client.new(region: region)# See Comment 1
resp = @ec2.describe_tags(
{
filters: [
{
name: "resource-id",
values: ["#{resource_id}"],
},
],
}
)# See comment 2
resp.to_h[:tags].find{|n| n[:key] == "Name"}[:value]
Comment 1:
Rspec actually got an array of hash, below is an example:
{:tags=>[{:key=>"Application", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"arn:aws:cloudformation:us-east-1:490780517948:stack/test-239-xg-standalone-783/ad0f61c0-43a6-11ea-8522-0a200f00c284"},
{:key=>"AutomationDowntime", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"off"},
{:key=>"AutomationExcluded", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"false"},
{:key=>"BusinessUnit", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"NSG"},
{:key=>"Component", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"UTM Base team"},
{:key=>"CostCentre", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"GB11602008"},
{:key=>"Environment", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"Test"},
{:key=>"Name", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"XG-test-239-xg-standalone-783-private"},
{:key=>"OwnerEmail", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"nsg-eng-team-test@test.com"},
{:key=>"OwnerName", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"Team test"},
{:key=>"Project", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"NSG-Dev"},
{:key=>"SecurityClassification", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"Low Business Impact"},
{:key=>"SupportEmail", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"nsg-eng-team-test@test.com"},
{:key=>"aws:cloudformation:logical-id", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"SubnetPrivate"},
{:key=>"aws:cloudformation:stack-id", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet",:value=>"arn:aws:cloudformation:us-east-1:490780517948:stack/test-239-xg-standalone-783/ad0f61c0-43a6-11ea-8522-0a200f00c284"},
{:key=>"aws:cloudformation:stack-name", :resource_id=>"subnet-009abbace367f2c03", :resource_type=>"subnet", :value=>"test-239-xg-standalone-783"}]}
Comment 2, this line returned the value of the item which key is ‘Name’. In above example, it returned “XG-test-239-xg-standalone-783-private”. You can use it get other hash’s key-value pair.