'What is best way to create invalidation after cloud formation created cloud front?
I am creating a completely serverless solution which will create an s3 bucket and CloudFront too. Using cloud formation template from bitbucket pipeline
I also want to create invalidate for CloudFront.
1) is it possible to create invalidation in cloud formation?
2) If no, then how can I get distribution id from my cloud formation and then create the invalidation using aws cli
CFDistribution:
Type: 'AWS::CloudFront::Distribution'
DependsOn: UIBucket
Properties:
DistributionConfig:
Aliases:
- !Sub "${AppSubDomain}.${SSMDomain}"
Origins:
- DomainName: !GetAtt UIBucket.DomainName
Id: S3BucketOrigin
S3OriginConfig:
OriginAccessIdentity: !Join
- ''
- - 'origin-access-identity/cloudfront/'
- !Ref CFOriginAccessIdentity
Comment: !Sub 'CloudFront origin for ${AppSubDomain}.${SSMDomain}'
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
- OPTIONS
TargetOriginId: S3BucketOrigin
ForwardedValues:
QueryString: 'false'
Cookies:
Forward: none
ViewerProtocolPolicy: redirect-to-https
DefaultRootObject: index.html
Enabled: 'true'
HttpVersion: http2
PriceClass: PriceClass_All
ViewerCertificate:
AcmCertificateArn: !Ref SSMWildcardCertificateARN
SslSupportMethod: sni-only
Tags:
- Key: "Type"
Value: "Host"
- Key: "Product"
Value: !Ref Product
- Key: "Environment"
Value: !Ref SSMEnvironment
Solution 1:[1]
I use CloudFront with CloudFormation too and I didn' find a way to create invalidation using CloudFormation. If you check AWS Docs, CloudFormation allows 3 types related to CloudFront
CloudFront
AWS::CloudFront::CloudFrontOriginAccessIdentity
AWS::CloudFront::Distribution
AWS::CloudFront::StreamingDistribution
and none of these create an invalidation. Answering your first question:
1) is it possible to create invalidation in cloud formation?
No.
2) If no, then how can I get distribution id from my cloud formation and then create the invalidation using aws cli
You can add distribution to CloudFormation template output:
Outputs:
CloudFrontDistributionID:
Description: 'CloudFront distribution ID'
Value: !Ref CloudFrontDistribution
CloudFrontURL:
Description: 'CloudFront URL'
Value:!GetAtt CloudFrontDistribution.DomainName
save distribution ID using bash (check this question):
$ distributionId=${aws cloudformation describe-stacks --stack-name MY_STACK --query "Stacks[0].Outputs[?OutputKey=='CloudFrontDistributionID'].OutputValue" --output text}
and, finally, create CloudFront invalidation:
$ aws cloudfront create-invalidation --distribution-id $distributionId --paths /index.html /error.html
Solution 2:[2]
You could use CloudFormation custom resources as well. You create a Lambda as a Custom Resource and invalidate the CloudFront cache there.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pedro Arantes |
Solution 2 | Andrés Miguel Bores Hevia |