Skip to content

Instantly share code, notes, and snippets.

@coord-e
Last active December 11, 2023 11:09
Show Gist options
  • Save coord-e/fa45002ea62877b895f45f2459b02cff to your computer and use it in GitHub Desktop.
Save coord-e/fa45002ea62877b895f45f2459b02cff to your computer and use it in GitHub Desktop.
require 'aws-sdk-ec2'
require 'aws-sdk-autoscaling'
ROUTE_TABLE_ID = ENV.fetch('ROUTE_TABLE_ID')
class Handler
def initialize
@ec2_client = Aws::EC2::Client.new
@autoscaling_client = Aws::AutoScaling::Client.new
end
def handle_launch(instance_id)
@ec2_client.modify_instance_attribute(
instance_id:,
source_dest_check: {
value: false,
},
)
@ec2_client.create_route(
destination_cidr_block: '0.0.0.0/0',
route_table_id: ROUTE_TABLE_ID,
instance_id: instance_id,
)
end
def handle_terminate(instance_id)
@ec2_client.delete_route(
destination_cidr_block: '0.0.0.0/0',
route_table_id: ROUTE_TABLE_ID,
)
rescue Aws::EC2::Errors::InvalidRouteNotFound
nil
end
def handle_event(event:)
detail = event.fetch('detail')
instance_id = detail.fetch('EC2InstanceId')
case event.fetch('detail-type')
when 'EC2 Instance-launch Lifecycle Action'
handle_launch(instance_id)
when 'EC2 Instance-terminate Lifecycle Action'
handle_terminate(instance_id)
end
@autoscaling_client.complete_lifecycle_action(
auto_scaling_group_name: detail.fetch('AutoScalingGroupName'),
lifecycle_action_result: 'CONTINUE',
lifecycle_action_token: detail.fetch('LifecycleActionToken'),
lifecycle_hook_name: detail.fetch('LifecycleHookName'),
)
end
end
def lambda_handler(event:, context:)
Handler.new.handle_event(event:)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment