如何在通过 cloudformation 编写 aws 策略时添加条件?

how to add a condition when writing a aws policy via cloudformation?

我正在通过 cloudformation 创建一些 IAM 角色和策略,但我想根据我的条件添加策略,比如如果它是开发人员,那么我想添加某些策略声明。有什么建议吗?

Parameters:
    environment:
        Type: String
        Default: dev
        AllowedValues:
            - dev
            - prd
Condition:
    isDev: !Equals [ !Ref environment, dev]

Resources:
  StandAlonePolicy:
    Type: AWS::IAM::Policy
    Properties:
      #How to add a condition - isDev
      PolicyName: "s3-policy"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Resource: "*"
          Action:
            - "s3:Get*"

您可以使用 If:

Parameters:
    environment:
        Type: String
        Default: dev
        AllowedValues:
            - dev
            - prd
Conditions:
    isDev: !Equals [ !Ref environment, dev]

Resources:
  StandAlonePolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: "s3-policy"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Resource: "*"
          Action:
            - "s3:Get*"
        - !If    
            - isDev
            - Sid: new-statement-for-dev-only
              Effect: Allow
              Resource: "*"
              Action:
                - "s3:Put*"
            - !Ref "AWS::NoValue"