Skip to content

Instantly share code, notes, and snippets.

@juliandunn juliandunn/awsha.rb
Last active Jan 25, 2018

Embed
What would you like to do?
Demo script for AWSAdvent 2014 blog post
#!/usr/bin/ruby
require 'fog'
require 'json'
require 'open-uri'
module AWSAdvent
class Demo
attr_reader :instance, :compute, :server
VIP = '172.31.36.57'.freeze
VOLUME = 'vol-deadbeef'.freeze
def initialize
@compute = Fog::Compute.new(:provider => 'AWS',
:use_iam_profile => true)
@instance = load_instance
@server = @compute.servers.get(@instance['instanceId'])
end
def action_master
# Take the elastic network interface IP address
puts "Binding ENI secondary to me"
@compute.assign_private_ip_addresses(@server.network_interfaces.first['networkInterfaceId'],
'PrivateIpAddresses' => [VIP],
'AllowReassignment' => true)
puts "Associating EBS device"
# Associate device
# Amazon's API names all devices /dev/sdXX, whereas newer Linuxes present them as device nodes /dev/xvdXX
@compute.attach_volume(@instance['instanceId'], VOLUME, '/dev/sdf')
# Wait for a while for it to get attached
sleep 30
# Mount disk if something's not already mounted
unless `mount`.split("\n").select { |l| l.include?('/mnt') }.length > 0
system('mount /dev/xvdf /mnt')
end
# Start httpd
system('service httpd start')
end
def action_backup
# Relinquish the elastic IP address -- nothing to do
# Stop httpd
system('service httpd stop')
# Dismount disk
system('umount /mnt')
# Disassociate device
@compute.detach_volume(VOLUME)
end
private
def load_instance
JSON.parse(open('http://169.254.169.254/latest/dynamic/instance-identity/document').read)
end
end
end
awsadvent = AWSAdvent::Demo.new
action = "action_#{ARGV[0]}".to_sym
if awsadvent.respond_to?(action)
awsadvent.send(action)
else
puts "Unknown action: #{ARGV[0]}"
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.