Skip to content

Instantly share code, notes, and snippets.

@adhorn
Created June 1, 2020 12:55
Show Gist options
  • Save adhorn/02241c4c558bd4e5c3f541a2efb55693 to your computer and use it in GitHub Desktop.
Save adhorn/02241c4c558bd4e5c3f541a2efb55693 to your computer and use it in GitHub Desktop.
Randomly stop EC2 instances using SSM Automation
---
description: Stop instances in a particular AZ with tag filter
schemaVersion: '0.3'
assumeRole: "{{ AutomationAssumeRole }}"
parameters:
AvailabilityZone:
type: String
description: "(Required) The Availability Zone to impact"
TagName:
type: String
description: "The tag name to filter instances"
TagValue:
type: String
description: "The tag value to filter instances"
AutomationAssumeRole:
type: String
description: "(Optional) The ARN of the role that allows Automation to perform
the actions on your behalf."
mainSteps:
- name: listInstances
action: aws:executeAwsApi
timeoutSeconds: 60
inputs:
Service: ec2
Api: DescribeInstances
Filters:
- Name: availability-zone
Values: ["{{ AvailabilityZone }}"]
- Name: instance-state-name
Values: ["running"]
- Name: tag:{{ TagName }}
Values: ["{{ TagValue }}"]
outputs:
- Name: InstanceIds
Selector: "$.Reservations..Instances..InstanceId"
Type: StringList
- name: verifyInstanceStateRunning
action: aws:waitForAwsResourceProperty
timeoutSeconds: 60
inputs:
Service: ec2
Api: DescribeInstanceStatus
InstanceIds:
- "{{ listInstances.InstanceIds }}"
PropertySelector: "$.InstanceStatuses[0].InstanceState.Name"
DesiredValues:
- running
- name: stopInstances
action: aws:changeInstanceState
onFailure: Continue
inputs:
InstanceIds: "{{ listInstances.InstanceIds }}"
DesiredState: stopped
- name: forceStopInstances
action: aws:changeInstanceState
inputs:
InstanceIds: "{{ listInstances.InstanceIds }}"
CheckStateOnly: false
DesiredState: stopped
Force: true
- name: verifyInstanceStateStopped
action: aws:waitForAwsResourceProperty
timeoutSeconds: 60
inputs:
Service: ec2
Api: DescribeInstanceStatus
IncludeAllInstances: true
InstanceIds:
- "{{ listInstances.InstanceIds }}"
PropertySelector: "$.InstanceStatuses[0].InstanceState.Name"
DesiredValues:
- stopped
- terminated
outputs:
- "listInstances.InstanceIds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment