Created
March 24, 2015 14:16
-
-
Save cognusion/7f48840e9a1babaa03cb to your computer and use it in GitHub Desktop.
Simple script to audit AWS EC2 Availability Zone usage, to spot imbalances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Audits the AZs your instances are running in, and reports back. | |
# If you want to run this from an AWS instance without keys, | |
# its IAM Role must be granted at least the following: | |
# | |
#{ | |
# "Statement": [ | |
# { | |
# "Action": [ | |
# "ec2:DescribeInstances", | |
# ], | |
# "Effect": "Allow", | |
# "Resource": "*" | |
# } | |
# ] | |
# } | |
require 'rubygems' | |
require 'trollop' # Option parsing made stupid easy | |
require 'aws-sdk' | |
require 'json' | |
require 'net/http' | |
class AZ | |
attr_accessor :name, :instances, :count | |
def initialize(name) | |
@name = name | |
@instances = Hash.new | |
@count = 0 | |
end | |
# Add a running instance (I) | |
def add_instance(entry) | |
@instances[entry] = @instances.has_key?(entry) ? @instances[entry] + 1 : 1 | |
@count += 1 | |
end | |
end | |
opts = Trollop::options do | |
opt :region, "AWS Region", | |
:type => String, | |
:default => 'us-east-1' | |
opt :localkeys, "Use local AWS credentials" | |
opt :csvreport, "Output report in CSV (TSV, actually)" | |
opt :verbose, "Spell out the variables" | |
opt :debug, "Be noisy" | |
end | |
# If you need to deal with keys/credentials, do that here. | |
ec2 = AWS::EC2.new(:region => opts[:region]) | |
AZs = Hash.new | |
# Collect running instances, add them to the appropriate AZ object | |
ec2.instances.each {|i| | |
next unless i.status.to_s == 'running' | |
puts "[d] I id: #{i.id} #{i.availability_zone} #{i.instance_type}" if opts[:debug] | |
unless AZs.has_key?(i.availability_zone) | |
AZs[i.availability_zone] = AZ.new(i.availability_zone) | |
end | |
AZs[i.availability_zone].add_instance(i.instance_type) | |
} | |
AZs.each_pair {|name, az| | |
puts "#{name}: #{az.count}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment