Skip to content

Instantly share code, notes, and snippets.

@hetul99
Created March 11, 2023 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hetul99/c71219a86b9ca1f04a893dcc6f3bbd60 to your computer and use it in GitHub Desktop.
Save hetul99/c71219a86b9ca1f04a893dcc6f3bbd60 to your computer and use it in GitHub Desktop.
import boto3
import json
import time
ssm = boto3.client('ssm')
def lambda_handler(event, context):
# Check if the event is a ModifyInstanceAttribute event and has an instance-type change
if event['detail']['eventName'] == 'ModifyInstanceAttribute' and \
event['detail']['requestParameters'].get('instanceType') is not None:
# Get the instance ID from the event
instance_id = event['detail']['requestParameters']['instanceId']
# Get the new instance type from the event
instance_type = event['detail']['requestParameters']['instanceType']
time.sleep(120)
# Execute the SSM document on the instance
response = ssm.send_command(
Targets=[
{
'Key': 'InstanceIds',
'Values': [instance_id]
}
],
DocumentName='AmazonCloudWatch-ManageAgent',
Parameters={
'action': ['configure'],
'mode': ['ec2'],
'optionalConfigurationSource': ['ssm'],
'optionalConfigurationLocation': ['AmazonCloudWatch-windows'],
'optionalRestart': ['yes']
}
)
# Get the command ID for the execution
command_id = response['Command']['CommandId']
# Return a success message with the command ID
return {
'statusCode': 200,
'body': json.dumps(f'Successfully executed AmazonCloudWatch-ManageAgent SSM document with command ID {command_id} for instance {instance_id} with new instance type {instance_type}')
}
else:
# Return a message indicating that the event is not a ModifyInstanceAttribute event with an instance-type change
return {
'statusCode': 200,
'body': json.dumps('Not a ModifyInstanceAttribute event with an instance-type change')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment