Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

18.4 KB
Raw Blame
# ---------------------------------------------------------------------------------------------------------------------
#
# CloudFormation Template for creating SSM Documents for attaching, detaching and replacing an EBS data volume
#
# ---------------------------------------------------------------------------------------------------------------------

AWSTemplateFormatVersion: "2010-09-09"
Description: "SSM documents for attaching, detaching and replacing an EBS data volume"
Resources:
  SSMMountVolumeDocument:
    Type: AWS::SSM::Document
    Properties:
      DocumentType: Command
      DocumentFormat: YAML
      TargetType: /AWS::EC2::Instance
      Name: mount_volume
      Content:
        schemaVersion: "2.2"
        description: "Script for mounting an EBS data volume"
        parameters:
          DeviceName:
            type: String
            description: "(Required) Specify the Device name where the volume should be mounted on"
            allowedPattern: "^/dev/sd[b-z]$"
        mainSteps:
          # Mount the specified EBS data volume to the instance
          - name: MountVolume
            action: aws:runShellScript
            inputs:
              runCommand:
                - |
                  FILESYSTEM=$(blkid -o value -s TYPE {{ DeviceName }})
                  if [ -z "$FILESYSTEM" ]; then
                    mkfs -t xfs {{ DeviceName }}
                    mount {{ DeviceName }} /var/lib/docker/volumes
                  else
                    mount {{ DeviceName }} /var/lib/docker/volumes
                  fi
          # Add the specified EBS data volume to the file system table
          - name: AddFileSystemEntry
            action: aws:runShellScript
            inputs:
              runCommand:
                - |
                  UUID=$(blkid -o value -s UUID {{ DeviceName }})
                  if [ -n "$UUID" ]; then
                    cp /etc/fstab /etc/fstab.orig
                    echo "UUID=$UUID /var/lib/docker/volumes xfs defaults,nofail 0 2" >> /etc/fstab
                  else
                    echo "Failed to add /etc/fstab entry .. UUID is not found"
                    exit 1
                  fi
          # Start the Docker service and socket
          - name: StartDocker
            action: aws:runShellScript
            inputs:
              runCommand:
                - systemctl start docker.socket docker.service

  SSMUmountVolumeDocument:
    Type: AWS::SSM::Document
    Properties:
      DocumentType: Command
      DocumentFormat: YAML
      TargetType: /AWS::EC2::Instance
      Name: umount_volume
      Content:
        schemaVersion: "2.2"
        description: "Script for umounting an EBS data volume"
        parameters:
          DeviceName:
            type: String
            description: "(Required) Specify the Device name where the volume is mounted on"
            allowedPattern: "^/dev/sd[b-z]$"
        mainSteps:
          # Stop the Docker service and socket
          - name: StopDocker
            action: aws:runShellScript
            inputs:
              runCommand:
                - systemctl stop docker.socket docker.service
          # Remove the specified EBS data volume from the file systems table
          - name: RemoveFileSystemEntry
            action: aws:runShellScript
            inputs:
              runCommand:
                - |
                  UUID=$(blkid -o value -s UUID {{ DeviceName }})
                  if [ -n "$UUID" ]; then
                    cp /etc/fstab /etc/fstab.orig
                    sed -i '/UUID='$UUID'/d' /etc/fstab
                  else
                    echo "Failed to remove /etc/fstab entry .. UUID is not found"
                    exit 1
                  fi
          # Umount the specified EBS data volume
          - name: UmountVolume
            action: aws:runShellScript
            inputs:
              runCommand:
                - |
                  MOUNT=$(findmnt -S {{ DeviceName }})
                  if [ -n "$MOUNT" ]; then
                    umount {{ DeviceName }}
                  else
                    echo "Device not mounted .. Skipping step"
                  fi

  SSMAttachVolumeDocument:
    Type: AWS::SSM::Document
    Properties:
      DocumentType: Automation
      DocumentFormat: YAML
      TargetType: /AWS::EC2::Instance
      Name: attach_volume
      Content:
        schemaVersion: "0.3"
        description: "Script for attaching an EBS data volume"
        parameters:
          VolumeId:
            type: String
            description: "(Required) Specify the VolumeId of the volume that should be attached"
            allowedPattern: "^vol-[a-z0-9]{8,17}$"
          InstanceId:
            type: String
            description: "(Required) Specify the InstanceId of the instance where the volume should be attached"
            allowedPattern: "^i-[a-z0-9]{8,17}$"
          DeviceName:
            type: String
            description: "(Required) Specify the Device name where the volume should be mounted on"
            allowedPattern: "^/dev/sd[b-z]$"
        mainSteps:
          # Retrieve instance details to get the Host name.
          - name: GetInstanceDetails
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeInstances
              InstanceIds:
                - "{{ InstanceId }}"
            outputs:
              - Name: Host
                Selector: $.Reservations[0].Instances[0].Tags[?(@.Key == 'Name')].Value
                Type: String
            nextStep: AttachVolume
          # Attach EBS data volume to specified instance
          - name: AttachVolume
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            isCritical: true
            inputs:
              Service: ec2
              Api: AttachVolume
              VolumeId: "{{ VolumeId }}"
              InstanceId: "{{ InstanceId }}"
              Device: "{{ DeviceName }}"
            nextStep: WaitForVolumeAttachment
          # Wait until the EBS data volume is successfully attached
          - name: WaitForVolumeAttachment
            action: aws:waitForAwsResourceProperty
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeVolumes
              VolumeIds:
                - "{{ VolumeId }}"
              PropertySelector: "$.Volumes[0].Attachments[0].State"
              DesiredValues:
                - attached
            nextStep: MountVolume
          # Mount EBS data volume to specified instance
          - name: MountVolume
            action: aws:runCommand
            timeoutSeconds: 120
            onFailure: Abort
            isCritical: true
            inputs:
              DocumentName: mount_volume
              Parameters:
                DeviceName:
                  - "{{ DeviceName }}"
              InstanceIds:
                - "{{ InstanceId }}"
            nextStep: WaitForVolumeMounting
          # Wait until the EBS data volume is successfully mounted
          - name: WaitForVolumeMounting
            action: aws:waitForAwsResourceProperty
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ssm
              Api: GetCommandInvocation
              CommandId: "{{ MountVolume.CommandId }}"
              InstanceId: "{{ InstanceId }}"
              PropertySelector: "$.StatusDetails"
              DesiredValues:
                - Success
            nextStep: UpdateTag
          # Change tag to ensure the EBS data volume is targeted by the DLM policy
          - name: UpdateTag
            action: aws:createTags
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              ResourceType: EC2
              ResourceIds:
                - "{{ VolumeId }}"
              Tags:
                - Key: Type
                  Value: "{{ GetInstanceDetails.Host }}-or-data-in-use"

  SSMDetachVolumeDocument:
    Type: AWS::SSM::Document
    Properties:
      DocumentType: Automation
      DocumentFormat: YAML
      TargetType: /AWS::EC2::Instance
      Name: detach_volume
      Content:
        schemaVersion: "0.3"
        description: "Script for detaching an EBS data volume"
        parameters:
          VolumeId:
            type: String
            description: "(Required) Specify the VolumeId of the volume that should be detached"
            allowedPattern: "^vol-[a-z0-9]{8,17}$"
        mainSteps:
          # Retrieve EBS data volume details to get the InstanceId and Devicename
          - name: GetVolumeDetails
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeVolumes
              VolumeIds:
                - "{{ VolumeId }}"
            outputs:
              - Name: InstanceId
                Selector: "$.Volumes[0].Attachments[0].InstanceId"
                Type: String
              - Name: DeviceName
                Selector: "$.Volumes[0].Attachments[0].Device"
                Type: String
            nextStep: GetInstanceDetails
          # Retrieve instance details to get the Hostname
          - name: GetInstanceDetails
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeInstances
              InstanceIds:
                - "{{ GetVolumeDetails.InstanceId }}"
            outputs:
              - Name: Host
                Selector: $.Reservations[0].Instances[0].Tags[?(@.Key == 'Name')].Value
                Type: String
            nextStep: UmountVolume
          # Execute the SSM command that umounts the specified EBS data volume
          - name: UmountVolume
            action: aws:runCommand
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              DocumentName: umount_volume
              Parameters:
                DeviceName:
                  - "{{ GetVolumeDetails.DeviceName }}"
              InstanceIds:
                - "{{ GetVolumeDetails.InstanceId }}"
            nextStep: WaitForUmount
          # Wait until the SSM document for umounting the EBS data volume is successfully executed
          - name: WaitForUmount
            action: aws:waitForAwsResourceProperty
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ssm
              Api: GetCommandInvocation
              CommandId: "{{ UmountVolume.CommandId }}"
              InstanceId: "{{ GetVolumeDetails.InstanceId }}"
              PropertySelector: "$.StatusDetails"
              DesiredValues:
                - Success
            nextStep: DetachVolume
          # Detach the EBS data volume
          - name: DetachVolume
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            isCritical: true
            inputs:
              Service: ec2
              Api: DetachVolume
              VolumeId: "{{ VolumeId }}"
            nextStep: WaitForVolumeDetachment
          # Wait until the EBS data volume is succesfully detached
          - name: WaitForVolumeDetachment
            action: aws:waitForAwsResourceProperty
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeVolumes
              VolumeIds:
                - "{{ VolumeId }}"
              PropertySelector: "$.Volumes[0].State"
              DesiredValues:
                - available
            nextStep: UpdateTag
          # Change tag to ensure the volume is no longer targeted by the DLM policy
          - name: UpdateTag
            action: aws:createTags
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              ResourceType: EC2
              ResourceIds:
                - "{{ VolumeId }}"
              Tags:
                - Key: Type
                  Value: "{{ GetInstanceDetails.Host }}-or-data-not-in-use"

  SSMReplaceVolumeDocument:
    Type: AWS::SSM::Document
    Properties:
      DocumentType: Automation
      DocumentFormat: YAML
      TargetType: /AWS::EC2::Instance
      Name: replace_volume
      Content:
        schemaVersion: "0.3"
        description: "Script for replacing an EBS data volume with a specified snapshot"
        parameters:
          VolumeId:
            type: String
            description: "(Required) Specify the VolumeId of the volume that needs to be replaced"
            allowedPattern: "^vol-[a-z0-9]{8,17}$"
          SnapshotId:
            type: String
            description: "(Required) Specify the SnapshotId of the snapshot to be used for the new volume"
            allowedPattern: "^snap-[a-z0-9]{8,17}$"
          DeleteVolume:
            type: Boolean
            description: "(Optional) Choose whether you want to delete the current volume"
            default: false
        mainSteps:
          # Retrieve EBS data volume details to get the DeviceName and InstanceId
          - name: GetVolumeDetails
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeVolumes
              VolumeIds:
                - "{{ VolumeId }}"
            outputs:
              - Name: InstanceId
                Selector: "$.Volumes[0].Attachments[0].InstanceId"
                Type: String
              - Name: DeviceName
                Selector: "$.Volumes[0].Attachments[0].Device"
                Type: String
            nextStep: GetInstanceDetails
          # Retrieve instance details to get the AvailabilityZone and Hostname
          - name: GetInstanceDetails
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeInstances
              InstanceIds:
                - "{{ GetVolumeDetails.InstanceId }}"
            outputs:
              - Name: AvailabilityZone
                Selector: "$.Reservations[0].Instances[0].Placement.AvailabilityZone"
                Type: String
              - Name: Host
                Selector: $.Reservations[0].Instances[0].Tags[?(@.Key == 'Name')].Value
                Type: String
            nextStep: CreateVolume
          # Create new EBS data volume using the retrieved details and specified snapshot
          - name: CreateVolume
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: CreateVolume
              AvailabilityZone: "{{ GetInstanceDetails.AvailabilityZone }}"
              SnapshotId: "{{ SnapshotId }}"
              VolumeType: gp3
              TagSpecifications:
                - ResourceType: volume
                  Tags:
                    - Key: Name
                      Value: "{{ GetInstanceDetails.Host }}-data"
                    - Key: Type
                      Value: "{{ GetInstanceDetails.Host }}-or-data-not-in-use"
            outputs:
              - Name: VolumeId
                Selector: "$.VolumeId"
                Type: String
            nextStep: WaitForVolumeCreation
          # Wait until the EBS data volume is succesfully created
          - name: WaitForVolumeCreation
            action: aws:waitForAwsResourceProperty
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DescribeVolumes
              VolumeIds:
                - "{{ CreateVolume.VolumeId }}"
              PropertySelector: "$.Volumes[0].State"
              DesiredValues:
                - available
            nextStep: DetachVolume
          # Detach the current EBS data volume
          - name: DetachVolume
            action: aws:executeAutomation
            timeoutSeconds: 120
            onFailure: Abort
            isCritical: true
            inputs:
              DocumentName: detach_volume
              RuntimeParameters:
                VolumeId:
                  - "{{ VolumeId }}"
            nextStep: WaitForVolumeDetachment
          # Wait until the current EBS data volume is succesfully detached
          - name: WaitForVolumeDetachment
            action: aws:waitForAwsResourceProperty
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ssm
              Api: GetAutomationExecution
              AutomationExecutionId: "{{ DetachVolume.ExecutionId }}"
              PropertySelector: "$.AutomationExecution.AutomationExecutionStatus"
              DesiredValues:
                - Success
            nextStep: AttachVolume
          # Attach the newly created EBS data volume
          - name: AttachVolume
            action: aws:executeAutomation
            timeoutSeconds: 120
            onFailure: Abort
            isCritical: true
            inputs:
              DocumentName: attach_volume
              RuntimeParameters:
                DeviceName:
                  - "{{ GetVolumeDetails.DeviceName }}"
                VolumeId:
                  - "{{ CreateVolume.VolumeId }}"
                InstanceId:
                  - "{{ GetVolumeDetails.InstanceId }}"
            nextStep: WaitForVolumeAttachment
          # Wait until the newly created EBS data volume is succesfully attached
          - name: WaitForVolumeAttachment
            action: aws:waitForAwsResourceProperty
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ssm
              Api: GetAutomationExecution
              AutomationExecutionId: "{{ AttachVolume.ExecutionId }}"
              PropertySelector: "$.AutomationExecution.AutomationExecutionStatus"
              DesiredValues:
                - Success
            nextStep: ChooseVolumeDeletion
          # Checks whether the old EBS data volume should be kept
          - name: ChooseVolumeDeletion
            action: aws:branch
            inputs:
              Choices:
                - NextStep: DeleteVolume
                  Variable: "{{ DeleteVolume }}"
                  BooleanEquals: true
            isEnd: true
          # Delete old EBS data volume if DeleteVolume variable is equal to true
          - name: DeleteVolume
            action: aws:executeAwsApi
            timeoutSeconds: 120
            onFailure: Abort
            inputs:
              Service: ec2
              Api: DeleteVolume
              VolumeId: "{{ VolumeId }}"