Created
July 6, 2020 09:41
-
-
Save morimorihoge/7cd8cf08062a12cac56ca98b6b91e4ed to your computer and use it in GitHub Desktop.
AWS Lambda Ruby 2.7 EC2 Instances Start
This file contains 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' | |
require 'json' | |
# Environments: | |
# AWS_REGION = 'ap-northeast-1' as default | |
# TARGET_INSTANCE_IDS = 'i-1234567890abcdef,i-2234567890abcdef' like comma-separated string | |
AWS_REGION = ENV['AWS_REGION'] || 'ap-northeast-1' | |
def lambda_handler(event:, context:) | |
target_instance_ids = ENV['TARGET_INSTANCE_IDS'].split(',') | |
result_messages = [] | |
client = Aws::EC2::Client.new(region: AWS_REGION) | |
result_messages << "Describe Instances: #{target_instance_ids}" | |
client.describe_instances(instance_ids: target_instance_ids).reservations.each do |reservation| | |
next if reservation.instances.count < 1 | |
reservation.instances.each do |i| | |
if i.state.name == 'stopped' | |
result_messages << "#{i.instance_id} is stopped. launching..." | |
client.start_instances(instance_ids: [i.instance_id]) | |
result_messages << "done" | |
else | |
result_messages << "#{i.instance_id} is not stopped" | |
end | |
end | |
end | |
result_messages << "start_instances Done" | |
client.wait_until(:instance_running, instance_ids: target_instance_ids) | |
result_messages << "instance_running confirmed" | |
{ statusCode: 200, body: result_messages.join("\n") } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment