Using Systems Manager Automation - Kahuna915/Capstone-Cloud-Integration GitHub Wiki

Steps to use a pre-created automation

  1. Enter Systems Manager Automation
  2. Execute Automation
    image
  3. Select a Document
    image
  4. Select where you would want it to execute (We are going to do Simple Execution)
    image
  5. Enter the Parameters
    image

YAML File to automate the creation of EC2 instances with the Cyberlocal-EC2 Tag

---
schemaVersion: '0.3'
description: Automate creation of EC2 instance with tag "Cyberlocal-EC2"
assumeRole: ''
parameters:
  InstanceType:
    type: String
    default: t2.micro
  ImageId:
    type: String
    default: ami-0c94855ba95c71c99
  SubnetId:
    type: String
    default: subnet-069ab8108ad7de9ec
  SecurityGroupId:
    type: String
    default: sg-07938df6b1b695291
  KeyName:
    type: String
    default: Cyberlocal
  TagValue:
    type: String
    default: Cyberlocal-EC2
mainSteps:
- name: Create_instance
  action: aws:runInstances
  inputs:
    InstanceType: '{{ InstanceType }}'
    ImageId: '{{ ImageId }}'
    SubnetId: '{{ SubnetId }}'
    SecurityGroupIds:
      - '{{ SecurityGroupId }}'
    KeyName: '{{ KeyName }}'
    TagSpecifications:
      - ResourceType: instance
        Tags:
          - Key: Name
            Value: '{{ TagValue }}'

YAML file to delete instances unless they have a specific tag

---
description: "Delete EC2 instances without 'cyberlocal-ec2' tag"
schemaVersion: "0.3"
assumeRole: ""
parameters:
  InstanceTagName:
    type: "String"
    default: "cyberlocal-ec2"
  Region:
    type: "String"
    default: "us-east-1"
mainSteps:
- name: "Find Instances"
  action: "aws:executeAwsApi"
  inputs:
    Service: "EC2"
    Api: "DescribeInstances"
    Filters:
    - Name: "tag-key"
      Values:
      - "{{ InstanceTagName }}"
  outputs:
    - Name: "InstanceIds"
      Selector: "$.Reservations[*].Instances[*].InstanceId"
- name: "Filter Instances"
  action: "aws:invokeLambdaFunction"
  inputs:
    FunctionName: "arn:aws:lambda:{{ Region }}:{{ AWSAccountId }}:function:FilterEC2Instances"
    Payload:
      InstanceIds: "{{ InstanceIds }}"
  outputs:
    - Name: "FilteredInstanceIds"
      Selector: "$.InstanceIds"
- name: "Terminate Instances"
  action: "aws:executeAwsApi"
  inputs:
    Service: "EC2"
    Api: "TerminateInstances"
    InstanceIds: "{{ FilteredInstanceIds }}"

Finished Product
image

Log Systems Manager Automation

Go in to the preferences and select Send output to CloudWatch
image

Troubleshooting

https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-troubleshooting.html

Sources

Sample Runbooks
Setting Up Automation