Cloudformation 更新堆栈名称或环境上的堆栈策略条件

时间:2021-04-16 11:53:32

标签: amazon-web-services amazon-cloudformation amazon-iam serverless policy

我的 CloudFormation 堆栈附加了一个策略:

{
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": [
        "Update:*"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Deny",
      "Principal": "*",
      "Resource": "*",
      "Action": [
        "Update:Replace",
        "Update:Delete"
      ],
      "Condition": {
        "StringEquals": {
          "ResourceType": [
            "AWS::SNS::Topic",
            "AWS::SQS::Queue"
          ]
        }
      }
    }
  ]
}

该政策可防止意外删除 SNS/SQS 资源。我想让政策在 dev 环境中更加宽松。如何有条件地禁用 Deny 语句,例如,如果我的 CF (cloudformation) 堆栈名称是 my-app-dev 或 CF 堆栈的标签 STAGE 等于 dev

顺便说一句,策略是由无服务器框架生成的,所以我必须将它写在 serverless.yml 中

1 个答案:

答案 0 :(得分:2)

这可以通过使用无服务器框架的环境变量来完成。

无服务器.yml

service: sample

provider:
  name: aws
  stage: ${opt:stage,"dev"}
  region: ap-northeast-1

custom:
  policyChange: 
    prd: Deny
    dev: Allow

resources:
  - ${file(iam.yml)}

iam.yml

Resources:
  SampleRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: SampleRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"
      Policies:
        - PolicyName: SamplePolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: '${self:custom.policyChange.${self:provider.stage}}'
              Resource: "*"
              Action:
              - sqs:*