Created
November 5, 2024 22:37
-
-
Save atheiman/7c6c0d54b0ad087bacedb096209af47b to your computer and use it in GitHub Desktop.
SSM automation document to set all EBS volumes attached to a given EC2 instance to delete on instance terminate
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
description: Set all EBS volumes of an EC2 instance to delete on instance termination | |
schemaVersion: '0.3' | |
parameters: | |
InstanceId: | |
type: String | |
AutomationAssumeRole: | |
type: String | |
default: 'arn:{{global:AWS_PARTITION}}:iam::{{global:ACCOUNT_ID}}:role/AWS-SystemsManager-AutomationExecutionRole' | |
description: >- | |
(Optional) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is | |
specified, Systems Manager Automation uses your IAM permissions to run this runbook. | |
assumeRole: "{{ AutomationAssumeRole }}" | |
mainSteps: | |
- name: SetDeleteOnTermination | |
action: 'aws:executeScript' | |
inputs: | |
Runtime: python3.11 | |
Handler: handler | |
InputPayload: | |
InstanceId: "{{ InstanceId }}" | |
Script: |- | |
import json | |
import boto3 | |
ec2 = boto3.client('ec2') | |
def handler(event,context): | |
inst = ec2.describe_instances(InstanceIds=[event['InstanceId']])['Reservations'][0]['Instances'][0] | |
print(json.dumps(inst['BlockDeviceMappings'], default=str)) | |
bdms = [] | |
for bdm in inst['BlockDeviceMappings']: | |
if 'Ebs' not in bdm: | |
continue | |
bdms.append({ | |
'DeviceName': bdm['DeviceName'], | |
'Ebs': {'DeleteOnTermination': True}, | |
}) | |
print(json.dumps(bdms, default=str)) | |
ec2.modify_instance_attribute( | |
InstanceId=event['InstanceId'], | |
BlockDeviceMappings=bdms, | |
) | |
inst = ec2.describe_instances(InstanceIds=[event['InstanceId']])['Reservations'][0]['Instances'][0] | |
bdms_json = json.dumps(inst['BlockDeviceMappings'], default=str) | |
print(bdms_json) | |
# JSON string return object renders nicely in automation console | |
return bdms_json | |
outputs: | |
- Name: Payload | |
Selector: "$.Payload" | |
Type: "String" | |
- Name: ExecutionLog | |
Selector: "$.ExecutionLog" | |
Type: "String" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment