5
votes

In AWS S3, you have the ability to visit the console and add 'Object-level logging' to a bucket. You create or select a pre-existing trail and select read and write log types.

Now I am creating buckets via Yaml CloudFormation and want to add a pre-existing trail (or create a new one) to these too. How do I do that? I can't find any examples.

2

2 Answers

6
votes

Object logging for S3 buckets with CloudTrail is done by defining so called event selectors for data events in CloudTrail. That is available through CloudFormation as well. The following CloudFormation template shows how that's done. The important part is in the lower half (the upper half is just for setting up an S3 bucket CloudTrail can log to):

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

For more details check out the CloudFormation documentation for CloudTrail event selectors.

0
votes

Though same only but this is how I have done it .

cloudtrail:
    Type: AWS::CloudTrail::Trail
    Properties:       
      EnableLogFileValidation: Yes
      EventSelectors: 
        - DataResources:
            - Type: AWS::S3::Object
              Values: 
                - arn:aws:s3:::s3-event-step-bucket/    
          IncludeManagementEvents: Yes
          ReadWriteType: All
      IncludeGlobalServiceEvents: Yes
      IsLogging: Yes
      IsMultiRegionTrail: Yes
      S3BucketName: s3-event-step-bucket-storage       
      TrailName: xyz