让 CloudFormation 堆栈自行删除的最佳方法是什么?

What is the best way to get a CloudFormation Stack to self-delete?

我正在尝试让我的 CloudFormation 堆栈在完成后自行删除。当我在模板中尝试以下代码时,日志显示找不到文件或命令。

当我使用 runuser 执行其他 AWS CLI 命令时没有问题(只要该命令不需要以“--”开头的选项)。

我正在使用基本的 AWS IAM。

          "06_delete_stack": { "command": { "Fn::Join": [ "", [
            "runuser -u fhwa 'aws cloudformation delete-stack --stack-name ", { "Ref": "StackName" }, "'"
          ] ] },
            "cwd": "/var/log"}

我能够让堆栈自行删除。

我让堆栈构建了一个额外的 shell 脚本,其中包含用于删除堆栈的 AWS CLI 命令。然后我调整了 runuser 命令来执行 shell 脚本。

然后我必须添加 IAM 权限以删除堆栈到生成的用户的角色。

扩展 , here's a minimal CloudFormation stack that self-destructs from an EC2 instance by running aws cloudformation delete-stack, with an AWS::IAM::Role 授予删除自身的最小权限:

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}

请注意,如果向模板添加任何其他资源,则需要将相应的 'delete' IAM 权限添加到 EC2Policy 语句列表。