Search code examples
amazon-web-servicesamazon-s3aws-cloudformationamazon-cloudfront

AWS S3 policy restrict only my cloudFrontdistribution (by yaml cloudFormation)


I want create AWS S3 policy. I want AWS S3 not public AND just access by my cloudFront distribution. I read all documentation but I do not find yaml sample.

I try this but I have an error (Policy has invalid):

BucketPolicy:
    Type: "AWS::S3::BucketPolicy"
    DependsOn: S3BucketFront
    Properties:
      Bucket: !Ref S3BucketFront
      PolicyDocument:
        Id: WebFrontBuildBucketPolicy
        Version: 2012-10-17
        Statement:
          - Sid: AllowCloudFrontServicePrincipal
            Effect: Allow
            Principal:
              Service:
                - cloudfront.amazonaws.com
            Action:
              - s3:GetObject
            Resource: "arn:aws:s3:::${AWS::AccountId}-${AWS::StackName}/*"
            Condition:
              StringEquals:
                "AWS:SourceArn": "arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontdistribution}"

EDIT

I took into account @Marcin's correction:

Resource: !Sub "arn:aws:s3:::${AWS::AccountId}-${AWS::StackName}/*"
Condition:
    StringEquals:
        "AWS:SourceArn": !Sub "arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontdistribution}"

Solution

  • You should use !Sub:

    Resource: !Sub "arn:aws:s3:::${AWS::AccountId}-${AWS::StackName}/*"
    

    Same for other places where you use CFN variables.