Terraform中aws_cloudfront_public_key无变更却重复重建的解决求助
解决Terraform中aws_cloudfront_public_key重复重建的问题
问题场景
使用以下Terraform代码创建CloudFront公钥资源:
resource "aws_cloudfront_public_key" "key" { name = "my-cf-pubkey" encoded_key = file("${path.module}/abcd.pem") }
首次执行terraform apply可成功创建资源,但后续每次执行时,即便本地公钥文件未做任何修改,aws_cloudfront_public_key仍会被销毁并重新创建。对应的Terraform Plan输出如下:
# aws_cloudfront_public_key.documents-signing-key must be replaced -/+ resource "aws_cloudfront_public_key" "documents-signing-key" { ~ caller_reference = "terraform-20221218060345896500000002" -> (known after apply) ~ encoded_key = <<-EOT # forces replacement -----BEGIN PUBLIC KEY----- -----END PUBLIC KEY----- EOT ~ etag = "E1PKWHEWOCNZS4" -> (known after apply) ~ id = "K15GFD3XARNT0X" -> (known after apply) name = "my-cf-pubkey" + name_prefix = (known after apply) # (1 unchanged attribute hidden) }
问题原因
核心问题是公钥内容的格式对比不一致:
- Terraform读取本地PEM文件时,会保留文件原有的空白字符(比如换行、空格)
- CloudFront API存储公钥后,返回的内容会自动去除多余空白,格式被标准化
两者格式差异导致Terraform判定encoded_key字段发生变更,触发资源重建。
解决方法
对本地读取的公钥内容做标准化处理,使其格式与CloudFront返回的一致。使用Terraform的字符串处理函数调整格式:
方案1:去除首尾空白并统一换行格式
resource "aws_cloudfront_public_key" "key" { name = "my-cf-pubkey" encoded_key = regex_replace(trimspace(file("${path.module}/abcd.pem")), "\\s+", "\n") }
方案2:更精准的格式调整
先用chomp去除文件末尾的换行,再替换所有连续空白为单个换行:
resource "aws_cloudfront_public_key" "key" { name = "my-cf-pubkey" encoded_key = chomp(regex_replace(file("${path.module}/abcd.pem"), "\\s+", "\n")) }
处理后,本地读取的公钥格式会和CloudFront存储的版本完全匹配,Terraform就不会再误触发资源重建操作。
内容的提问来源于stack exchange,提问作者Jatin Panchal
相关产品推荐
相关产品推荐

