Bug-Byte 3: Intrinsic function import failing on CloudFormation stack deployment
This bug is specific to deploying CloudFormation templates through a CI/CD pipeline, in this case Gitlab. If you are using the intrinsic function Fn::Import statements in your templates, you may have run into this error message
"Template error: the attribute in Fn::ImportValue must not depend on any resources, imported values, or Fn::GetAZs"
If so, the likely culprit is a reference typo within your import statement. However, if you’ve given the template a once-over and haven’t found any errors, consider checking the deployment script. When I make use of the Import function in CloudFormation, I often pass a stack name from the CI script to the template as a parameter to allow the name of the import target to be dynamically constructed. This allows for more flexibility in using the template, but introduces more opportunities for typos. If there is an error in that parameter, CloudFormation will be unable to resolve the Import, and will throw the above error.
variables:
environment: production
stages:
- deploy
deploy-s3:
stage: deploy
variables:
stackName: example-s3
kmsStack: exple-kms # TYPO: Actual Kms stack is named “example-kms”
only:
- main
script:
- aws cloudformation deploy --template-file ./ec2.yml
--stack-name $stackName
--no-execute-changeset --no-fail-on-empty-changeset
--tags environment=$environment
--parameter
- aws cloudformation wait stack-exists --stack-name $stackName
- aws cloudformation update-termination-protection
--stack-name $stackName
--enable-termination-protection
Example CloudFormation template
AWSTemplateFormatVersion: 2010-09-09
Description: Deploy S3 bucket
Parameters:
kmsStack:
Type: String
Resources:
bucket0:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
KMSMasterKeyID: { 'Fn::ImportValue': !Sub '${kmsStack}-arn' }
SSEAlgorithm: aws:kms
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
In the above example, cloudformation would fail to resolve a valid import target, assuming the kms key export is named example-kms-arn.
Remember to check your imports.
Hope that helped. Good luck out there in the cloud.