如何在云模板中编写存储桶策略

时间:2017-06-06 14:25:25

标签: amazon-web-services amazon-s3 amazon-cloudformation

我准备了一个云模板,可以使用AWS::IAM::Role政策创建arn:aws:iam::aws:policy/AmazonS3FullAccess

模板成功运行后,我执行python脚本创建两个前缀为foobar-bucket1foobar-bucket2的存储桶。

目前,我的模板的上一部分是这样的:

Resources:
  MyRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ssm.amazonaws.com
            - ec2.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/AmazonS3FullAccess
      Path: "/"

问题

我想知道是否需要通过云模板创建IAM::Role来创建AmazonS3FullAccess以创建两个存储桶?

我是否可以授予角色 ONLY 权限来创建存储桶,然后在带有前缀foobar-bucket1和{{1}的存储桶上提供 ONLY 的权限}}。

1 个答案:

答案 0 :(得分:1)

只要存储桶名称是动态的,您就无法在您的cloudformation模板中创建具有正确名称的策略。

按实用性降序排列:

选项1:在您的cloudformation模板中创建存储桶,然后在同一模板中相应地创建IAM角色(请参阅下面的示例)。

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  foobarBucket1:
    Type: AWS::S3::Bucket
  foobarBucket2:
    Type: AWS::S3::Bucket
  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"
      Policies:
        - PolicyName: LambdaRolePolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action:
              - s3:DeleteObject
              - s3:GetObject
              - s3:PutObject
              Resource: !Join ['', ['arn:aws:s3:::', !Ref foobarBucket1 ]]
            - Effect: Allow
              Action:
              - s3:DeleteObject
              - s3:GetObject
              - s3:PutObject
              Resource: !Join ['', ['arn:aws:s3:::', !Ref foobarBucket2 ]]

选项2:另一种可能是您将固定前缀合并到策略中,从而部分限制访问。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::foobarbucket1-*",
            "Effect": "Allow"
        }
    ]
}

选项3:使用存储桶名称作为cloudformation参数,并使用新创建的名称更新现有模板。