0
votes

I want to create a terminable Cloudformation stack to run a batch job that terminates itself afterwards. So i want a Cloudformation template with EC2 instance that has IAM role to terminate that Cloudformation stack.

1
What have you done so far? Where you are stuck? what are your findings? Neither it is a wish list up-loader site nor it's all users Santa claus. Please provide some starting point where in we can help. - Manish Joshi
Cloudformation is not the solution you are looking for. Try AWS Lambda or AWS Data Pipeline. - helloV

1 Answers

0
votes

Here's a minimal CloudFormation stack that self-destructs from an EC2 instance by running aws cloudformation delete-stack:

Launch Stack

Description: Cloudformation stack that self-destructs
Mappings:
  # amzn-ami-hvm-2016.09.1.20161221-x86_64-gp2
  RegionMap:
    us-east-1:
      "64": "ami-9be6f38c"
Resources:
  EC2Role:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "EC2Role-${AWS::StackName}"
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
        - Effect: Allow
          Principal:
            Service: [ ec2.amazonaws.com ]
          Action: [ "sts:AssumeRole" ]
      Path: /
      Policies:
      - PolicyName: EC2Policy
        PolicyDocument:
          Version: 2012-10-17
          Statement:
          - Effect: Allow
            Action:
            - "cloudformation:DeleteStack"
            Resource: !Ref "AWS::StackId"
          - Effect: Allow
            Action: [ "ec2:TerminateInstances" ]
            Resource: "*"
            Condition:
              StringEquals:
                "ec2:ResourceTag/aws:cloudformation:stack-id": !Ref AWS::StackId
          - Effect: Allow
            Action: [ "ec2:DescribeInstances" ]
            Resource: "*"
          - Effect: Allow
            Action:
            - "iam:RemoveRoleFromInstanceProfile"
            - "iam:DeleteInstanceProfile"
            Resource: !Sub "arn:aws:iam::${AWS::AccountId}:instance-profile/*"
          - Effect: Allow
            Action:
            - "iam:DeleteRole"
            - "iam:DeleteRolePolicy"
            Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/EC2Role-${AWS::StackName}"
  RootInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: /
      Roles: [ !Ref EC2Role ]
  WebServer:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !FindInMap [ RegionMap, !Ref "AWS::Region", 64 ]
      InstanceType: m3.medium
      IamInstanceProfile: !Ref RootInstanceProfile
      UserData:
        "Fn::Base64":
          !Sub |
            #!/bin/bash
            aws cloudformation delete-stack --stack-name ${AWS::StackId} --region ${AWS::Region}

Note that if you add any additional resources, you'll need to add the corresponding 'delete' IAM permission to the EC2Policy statement list.