Access Denied when calling the CreateInvalidation operation on AWS CLI

amazon-web-servicesaws-cli

I am attempting to create a command that will invalidate CloudFront distribution when pushing out new code. This is an attempt to fix the issue that new HTML pushed out doesn't take up to 24 hours to appear on my web app. The idea comes from this AWS CLI COMMAND REFERENCE

Here is the command:

aws cloudfront create-invalidation --distribution-id XXXXXXXXXXXXXX --invalidation-batch file://invbatch.json

Here is the response I get when I run the command:

A client error (AccessDenied) occurred when calling the CreateInvalidation operation: User: arn:aws:iam::XXXXXXXXXXXXXX:user/cats-kittens-beanstalk-user is not authorized to perform: cloudfront:CreateInvalidation

Any idea why this might be? I know AWS throws this access denied even though the user is authorized to run commands in some instances – see here.

Best Answer

IAM Policies do not allow restriction of access to specific CloudFront distributions. The solution is to use a wildcard for the resource, instead of only referencing a specific CloudFront resource. Adding that to your IAM policy will fix the issue you're having.

Here is an example of that in a working IAM policy:

{
  "Statement": [  
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "cloudfront:CreateInvalidation",
        "cloudfront:GetInvalidation",
        "cloudfront:ListInvalidations"
      ],
      "Resource": "*"
    }
  ]
}

Docs: