ses 角色的 AWS CloudFormation 环境条件

AWS CloudFormation environmental conditional for ses role

我正在尝试制作一个可重用的 CloudFormation 模板,并希望在环境参数为 "test"(或 "prod" 以外的任何其他环境)的情况下执行某种条件,然后仅向 gmail 帐户(即公司帐户)发送 SES 电子邮件,但对于 "prod",向任何地方发送 SES 电子邮件。我是否必须扮演两个不同的角色并且对每个角色都有条件?或者有没有办法在下面的一个角色中做到这一点?感谢您的帮助!

Parameters: 

  Environment:
    Description: Environment, which can be "test", "stage", "prod", etc.
    Type: String

 Resources:

   Role: 
    Type: AWS::IAM::Role
    Properties: 
    RoleName: myRole
    Path: /
    AssumeRolePolicyDocument: 
       Version: "2012-10-17"
       Statement:
        - 
          Effect: "Allow"
          Principal: 
            Service: 
              - "ecs.amazonaws.com"
          Action: 
            - "sts:AssumeRole" 
    Policies: 
      - 
        PolicyName: "ses-policy"
        PolicyDocument:
          Version: "2012-10-17"
          Statement: 
            -
              Effect: "Allow"
              Action: 
                - "ses:SendEmail"
                - "ses:SendRawEmail"
              Resource: "*"
              Condition:
                "ForAllValues:StringLike": 
                  "ses:Recipients": 
                    - "*@gmail.com"

Conditions are perfectly suited for adding this sort of conditional logic to CloudFormation Resource Properties. In your example, you could use the Fn::If Intrinsic Function to include the existing Policy Condition (not to be confused with the CloudFormation Condition!) if the environment is not prod, and AWS::NoValue 否则(当环境为 prod 时完全删除策略条件):

Parameters:
  Environment:
    Description: Environment, which can be "test", "stage", "prod", etc.
    Type: String
    AllowedValues: [test, stage, prod]
Conditions:
  IsProdEnvironment: !Equals [ !Ref Environment, prod ]
Resources:
  Role:
    Type: AWS::IAM::Role
    Properties:
      RoleName: myRole
      Path: /
      AssumeRolePolicyDocument:
         Version: "2012-10-17"
         Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - "ecs.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      Policies:
        -
          PolicyName: "ses-policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: "Allow"
                Action:
                  - "ses:SendEmail"
                  - "ses:SendRawEmail"
                Resource: "*"
                Condition: !If
                - IsProdEnvironment
                - !Ref AWS::NoValue
                - "ForAllValues:StringLike":
                    "ses:Recipients":
                      - "*@gmail.com"