amazon-web-servicesaws-lambdaaws-cloudformationamazon-cloudfrontaws-lambda-edge

Unable to add cloudfront as trigger to lambda function


Hi I've followed this instruction try to resize image with Cloudfront and lambda@edge. When I tried to test the resized image, I keep getting the error message below:

The Lambda function associated with the CloudFront distribution is invalid or doesn't have the required permissions.

So I checked the lambda functions created by cloud formation provided by the article I mentioned in the beginning, and I found there's no trigger in it.

enter image description here

I've tried to set it manually but getting the error message below:

CloudFront events cannot be associated with $LATEST or Alias. Choose Actions to publish a new version of your function, and then retry association.

I followed the instruction in the error message; publish, and add Cloudfront as trigger but it seems there's no way to apply it. It's still running the one without Cloudfront as the trigger.

How can I apply this version as my lambda service?

Is there any way to set Cloudfront as trigger and make this work properly?


Solution

  • For other ppl suffering from the poor quality of dev articles from aws blog; I found it's due to the wrong S3 bucket policy. The article says:

    ImageBucketPolicy:
        Type: AWS::S3::BucketPolicy
        Properties:
          Bucket: !Ref ImageBucket
          PolicyDocument:
            Statement:
                - Action:
                    - s3:GetObject
                  Effect: Allow
                  Principal: "*"
                  Resource: !Sub arn:aws:s3:::${ImageBucket}/*
                - Action:
                    - s3:PutObject
                  Effect: Allow
                  Principal:
                    AWS: !GetAtt EdgeLambdaRole.Arn
                  Resource: !Sub arn:aws:s3:::${ImageBucket}/*
                - Action:
                    - s3:GetObject
                  Effect: Allow
                  Principal:
                    AWS: !GetAtt EdgeLambdaRole.Arn
                  Resource: !Sub arn:aws:s3:::${ImageBucket}/*
    

    It turns out you have to grant the permissions to allow other actions besides of GetObject and PutObject, because it needs to create folders in the bucket. Simply the problem is resolved by changing it to s3:*