-
-
Save toddlers/c1beac9e3fb3120e9f68 to your computer and use it in GitHub Desktop.
Run OpsWorks Stack command on Instance
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
| require 'aws-sdk-v1' | |
| require 'pp' | |
| AWS_KEY_ID = ENV['AWS_KEY_ID'] | |
| AWS_SEC_KEY = ENV['AWS_SEC_KEY'] | |
| opsw = AWS::OpsWorks.new(access_key_id: AWS_KEY_ID, secret_access_key: AWS_SEC_KEY) | |
| @opsw_cli = opsw.client | |
| def retrieve_stacks(region = nil, stack_prefix_hint = nil) | |
| response = @opsw_cli.describe_stacks | |
| stacks = response.data[:stacks] | |
| stacks = stacks.select do |s| | |
| (region.nil? || s[:region] == region) && | |
| (stack_prefix_hint.nil? || s[:name].start_with?(stack_prefix_hint)) | |
| end | |
| end | |
| def retrieve_instances(stack) | |
| response = @opsw_cli.describe_instances(stack_id: stack[:stack_id]) | |
| response.data[:instances] | |
| end | |
| def search_instance(hostname, region = nil, stack_prefix_hint = nil) | |
| retrieve_stacks(region, stack_prefix_hint).each do |stack| | |
| retrieve_instances(stack).each do |instance| | |
| return instance if instance[:hostname] == hostname | |
| end | |
| end | |
| nil | |
| end | |
| def run_command(instance, command = :configure) | |
| option = { | |
| stack_id: instance[:stack_id], | |
| command: { name: command.to_s, }, | |
| instance_ids: [ | |
| instance[:instance_id] | |
| ], | |
| } | |
| @opsw_cli.create_deployment(option) | |
| end | |
| # main | |
| hostname = "<target-instancename>" | |
| region = nil | |
| stack_prefix_hint = nil | |
| command = "configure" | |
| instance = search_instance(hostname, region, stack_prefix_hint) | |
| if instance | |
| puts "Start running a command - hostname:#{hostname} command:#{command}" | |
| pp run_command(instance, command) | |
| else | |
| $stderr.puts "Error: Failed to find an instance - #{hostname}" | |
| exit 1 | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment