EXCELでAWSタグ管理する CSV形式アップロード・ダウンロード用Rubyスクリプト

EXCELを使ってAWSのタグを管理するツールです。と言ってもCSVでExport/Importするだけですが。


事前準備1 AWS SDK for Rubyインストール

何はともあれAWS SDK for Rubyのインストール

gem install aws-sdk

https://aws.amazon.com/jp/sdk-for-ruby/


事前準備2 アクセスキーの準備

WindowsLinuxMacそれぞれ規定のファイルにアクセスキーをセットします。

Windowsの場合

%USERPROFILE%\.aws\credentials

Linux/Macの場合

~/.aws/credentials

とりあえず今回はデフォルトのCredentialを使います。細かいことは割愛。

[default]
aws_access_key_id = ACCESS_KEY_ID
aws_secret_access_key = SECRET_ACCESS_KEY

A New and Standardized Way to Manage Credentials in the AWS SDKs - AWS Security Blog

使い方

以下の画面の通り、EBSにいくつかタグが設定してありますが、歯抜け状態です。
f:id:yomon8:20160125195101p:plain

まずは「get-awstags-to-csv.rb」を使ってタグ情報をCSVファイルにダウンロードします。

./get-awstags-to-csv.rb -o awstag.csv -r ap-northeast-1

CSVファイルなので、EXCELで開くことができます。
f:id:yomon8:20160125195104p:plain

開いてみました。当然こちらも歯抜け状態です。
f:id:yomon8:20160125195107p:plain

使い慣れたEXCELでタグを設定します。新しいタグ「MyTag」も追加してみました。
f:id:yomon8:20160125195110p:plain

CSV形式で保存します。
f:id:yomon8:20160125195113p:plain

今度は「set-awstags-from-csv.rb」を使ってCSVに設定したタグをアップロードしてみます。

./set-awstags-from-csv.rb -i awstag.csv -r ap-northeast-1

AWSの画面で見るとしっかりCSVの情報が反映されているのがわかります。
f:id:yomon8:20160125195117p:plain

ソースコード

get-awstags-to-csv.rb

#!/usr/bin/env ruby
require 'csv'
require 'optparse'
require 'aws-sdk-core'

options = {}
OptionParser.new do |opt|
  begin
    opt.on('-o VALUE', '--output-file VALUE', 'specify the output file path') { |v| options[:o] = v}
    opt.on('-r VALUE', '--region VALUE', 'specify the AWS region, e.g. us-west-2') { |v| options[:r] = v}
    opt.parse!(ARGV)
    if options.length != 2
      puts opt.help
      exit 1
    end
  rescue => e
    $stderr.puts e
    exit 1
  end
end

output_file = options[:o]
region = options[:r]

cred = Aws::SharedCredentials.new
Aws.use_bundled_cert!
ec2_client = Aws::EC2::Client.new(credentials: cred, region: region)

tags = ec2_client.describe_tags.tags.select do |t| !t.key.start_with?('aws:') end 
tag_keys = %w(ResourceId Name)
tags.uniq do |t| 
  t.key 
end.each do |ut|
  if !tag_keys.include?(ut.key) 
   tag_keys.push(ut.key)
  end
end

resource_ids = tags.uniq do |t| 
  t.resource_id
end.collect do |ut| 
  ut.resource_id 
end

tag_data = []
resource_ids.each do |rid|
  row = Array.new(tag_keys.length)
  row[tag_keys.index("ResourceId")] = rid
  tags.select do |t|
    t.resource_id == rid 
  end.each do |rt|
    row[tag_keys.index(rt.key)] = rt.value  
  end
  tag_data.push(row)
end

CSV.open(output_file, 'wb', encoding:"Shift_JIS:UTF-8") do |csv|
  csv << tag_keys
  tag_data.each do | row |
    csv <<  row
  end
end

set-awstags-from-csv.rb

#!/usr/bin/env ruby
require 'csv'
require 'optparse'
require 'aws-sdk-core'

options = {}
OptionParser.new do |opt|
  begin
    opt.on('-i VALUE', '--input-file VALUE', 'specify the input file path') { |v| options[:i] = v}
    opt.on('-r VALUE', '--region VALUE', 'specify the AWS region, e.g. us-west-2') { |v| options[:r] = v}
    opt.parse!(ARGV)
    if options.length != 2
      puts opt.help
      exit 1
    end
  rescue => e
    $stderr.puts e
    exit 1
  end
end
inpurt_file = options[:i]
region = options[:r]

cred = Aws::SharedCredentials.new
Aws.use_bundled_cert!
ec2_client = Aws::EC2::Client.new(credentials: cred, region: region)
header = []
CSV.foreach(inpurt_file, encoding: "Shift_JIS:UTF-8") do |row|
   if header.empty? 
     row.each do |field| header.push(field) end
   else
     tag_key_value_pair = []
     resource_id = nil
     row.each.with_index(0) do |tag_value,index|
       if index == header.index("ResourceId")
         resource_id = tag_value
       else
         if tag_value
           tag_key_value_pair.push({'key' => header[index],'value' => tag_value })
         end
       end
     end
     begin
       ec2_client.create_tags(resources:[resource_id] ,tags:tag_key_value_pair)
     rescue => ex
       puts "Failed to create tags!"
       puts "ResourceId :#{resource_id}"
       puts "Error Mesage:#{ex.message}"
     end
   end
end