通过 cloudformation 在 s3 存储桶上启用对象日志记录

Pau*_*aul 5 amazon-s3 amazon-web-services aws-cloudformation amazon-cloudtrail

在 AWS S3 中,您可以访问控制台并将“对象级日志记录”添加到存储桶。您创建或选择预先存在的跟踪并选择读取和写入日志类型。

现在我正在通过 Yaml CloudFormation 创建存储桶,并希望向这些添加一个预先存在的跟踪(或创建一个新的)。我怎么做?我找不到任何例子。

Dun*_*dan 6

使用 CloudTrail 对 S3 存储桶进行对象日志记录是通过为 CloudTrail 中的数据事件定义所谓的事件选择器来完成的。这也可以通过 CloudFormation 获得。以下 CloudFormation 模板展示了如何做到这一点。重要的部分在下半部分(上半部分仅用于设置 CloudTrail 可以登录的 S3 存储桶):

AWSTemplateFormatVersion: "2010-09-09"

Resources:
  s3BucketForTrailData:
    Type: "AWS::S3::Bucket"
  trailBucketPolicy:
    Type: "AWS::S3::BucketPolicy"
    Properties:
      Bucket: !Ref s3BucketForTrailData
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Principal:
            Service: "cloudtrail.amazonaws.com"
          Action: "s3:GetBucketAcl"
          Resource: !Sub "arn:aws:s3:::${s3BucketForTrailData}"
        - Effect: Allow
          Principal:
            Service: "cloudtrail.amazonaws.com"
          Action: "s3:PutObject"
          Resource: !Sub "arn:aws:s3:::${s3BucketForTrailData}/AWSLogs/${AWS::AccountId}/*"
          Condition:
            StringEquals:
              "s3:x-amz-acl": "bucket-owner-full-control"

  s3BucketToBeLogged:
    Type: "AWS::S3::Bucket"
  cloudTrailTrail:
    Type: "AWS::CloudTrail::Trail"
    DependsOn:
      - trailBucketPolicy
    Properties:
      IsLogging: true
      S3BucketName: !Ref s3BucketForTrailData
      EventSelectors:
        - DataResources:
            - Type: "AWS::S3::Object"
              Values:
                - "arn:aws:s3:::"  # log data events for all S3 buckets
                - !Sub "${s3BucketToBeLogged.Arn}/"  # log data events for the S3 bucket defined above
          IncludeManagementEvents: true
          ReadWriteType: All
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看CloudTrail 事件选择器的 CloudFormation 文档