Skip to content

Instantly share code, notes, and snippets.

@JAMSUPREME
Last active February 11, 2024 02:14
Show Gist options
  • Save JAMSUPREME/ad74f49b5619428a04d20ab57e605125 to your computer and use it in GitHub Desktop.
Save JAMSUPREME/ad74f49b5619428a04d20ab57e605125 to your computer and use it in GitHub Desktop.
SSM Automation
description: |-
### EC2 stopper by tag
Stop EC2 instances by tag
schemaVersion: '0.3'
mainSteps:
- name: getInstancesByTag
action: 'aws:executeAwsApi'
outputs:
- Name: InstanceIds
Selector: $.Reservations..Instances..InstanceId
Type: StringList
inputs:
Service: ec2
Api: describe-instances
Filters:
- Name: 'tag:Sleepable'
Values:
- 'true'
- name: stopEC2s
action: 'aws:changeInstanceState'
inputs:
InstanceIds: '{{getInstancesByTag.InstanceIds}}'
DesiredState: stopped
description: Stops the EC2 instances
description: Get RDS instances and stop them
schemaVersion: '0.3'
# Needs a suitable role or the boto stuff will fail
assumeRole: 'arn:aws:iam::368807016378:role/ssm-runner'
mainSteps:
- name: getRdsInstancesByTag
action: 'aws:executeAwsApi'
outputs:
- Selector: $.ResourceTagMappingList..ResourceARN
Type: StringList
Name: InstanceArns
inputs:
Service: resourcegroupstaggingapi
Api: GetResources
TagFilters:
- Key: Sleepable
Values:
- 'true'
ResourceTypeFilters:
- 'rds:db'
description: Get RDS instances by tag
- name: getInstanceIds
action: 'aws:executeAwsApi'
inputs:
Service: rds
Api: DescribeDBInstances
Filters:
- Name: db-instance-id
Values:
- '{{getRdsInstancesByTag.InstanceArns}}'
- Name: engine
Values:
- postgres
- mysql
outputs:
- Name: dbInstanceIds
Selector: $.DBInstances..DBInstanceIdentifier
Type: StringList
description: >-
Get instance ID via ARN.
This is a bit frivolous since the ID is the suffix of the ARN, but I don't
see any substring function we can run in this scope.
- name: stopInstances
action: 'aws:executeScript'
inputs:
Runtime: python3.7
Handler: script_handler
Script: |-
def script_handler(events, context):
import boto3
rds_client = boto3.client('rds')
print(f"The IDsto terminate are {events['instanceIds']}")
instance_ids = events['instanceIds']
for instance_id in instance_ids:
print(f"About to stop {instance_id}")
rds_client.stop_db_instance(DBInstanceIdentifier=instance_id)
return {'message': 'Stopped stuff'}
InputPayload:
instanceIds: '{{getInstanceIds.dbInstanceIds}}'
description: Stop RDS instances
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment