読者です 読者をやめる 読者になる 読者になる

AWS EC2のタグを関連するEBSとENIにコピーするスクリプト

結構前に一回実行用に作ったものだけど、最近使う機会出たのでここにもメモ。

#!/usr/bin/env ruby
require 'aws-sdk'
require 'pp'

region = 'ap-northeast-1'
cred = Aws::SharedCredentials.new
Aws.use_bundled_cert!
cli = Aws::EC2::Client.new(credentials: cred, region: region)

instance_info = cli.describe_instances
all_instances = instance_info[0].map do |data|
  data[:instances].first
end

all_instances.each do |instance|
  instance_tags = instance.tags.select{|t| !t.key.start_with?('aws')}.map {|t| {:key => t.key,:value => t.value}}
  pp "Set Tag :#{instance_tags}"
  instance.block_device_mappings.map {|b| b.ebs.volume_id}.each {|id| cli.create_tags(resources: [id],tags: instance_tags)}
  instance.network_interfaces.map {|n| n.network_interface_id}.each {|id| cli.create_tags(resources: [id],tags: instance_tags)}
end