You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform未识别AWS S3 Object资源问题排查求助

Terraform无法生成AWS S3 Object资源的排查与解决

多次尝试后发现,Terraform可正常创建S3 Bucket及Bucket网站配置资源,但S3 Object资源始终无法生成,相关代码如下:

resource "aws_s3_bucket" "My_bucket" {
  bucket = "my-test-bucket-for-cloudfront"
  tags = {
    Name = "My bucket"
  }
}

resource "aws_s3_bucket_public_access_block" "public_bucket" {
  bucket = aws_s3_bucket.My_bucket.id

  block_public_acls       = false
  block_public_policy     = false
  ignore_public_acls      = false
  restrict_public_buckets = false
}

resource "aws_s3_object" "object" {
  # Use a for loop to grab every file in the folder.
  # The fileset() function is used to read all the files in a folder
  for_each = fileset("/travel-agency-html-template/", "**")
  bucket = "my-test-bucket-for-cloudfront"
  # Use each.value to grab every file inside the folder
  key    = each.value
  source = "/travel-agency-html-template/${each.value}"
  acl = "public-read"
  etag = filemd5("travel-agency-html-template/${each.value}")

  depends_on = [ aws_s3_bucket.My_bucket ]
}

resource "aws_s3_bucket_website_configuration" "travel_agency" {
  bucket = aws_s3_bucket.My_bucket.id

  index_document {
    suffix = "/travel-agency-html-template/index.html"
  }

  error_document {
    key = "/travel-agency-html-template/404.html"
  }
}

问题排查与修复要点

  • 路径问题(核心原因):
    代码中使用绝对路径/travel-agency-html-template/,若该路径在Terraform执行环境中不存在或权限不足,fileset会返回空集合,直接导致无Object资源生成。建议改用相对路径(假设模板文件夹与Terraform配置文件同目录),修改如下:

    for_each = fileset("./travel-agency-html-template/", "**")
    source = "./travel-agency-html-template/${each.value}"
    etag = filemd5("./travel-agency-html-template/${each.value}")
    

    可通过terraform console执行fileset("./travel-agency-html-template/", "**")验证是否能读取到文件列表。

  • ETag路径不一致:
    原代码中filemd5的参数缺少开头斜杠,与source路径不匹配,可能导致文件读取失败,需保持路径完全一致。

  • Bucket名称硬编码:
    直接引用Bucket资源的属性替代硬编码名称,提升代码健壮性,避免Bucket名称修改后代码未同步:

    bucket = aws_s3_bucket.My_bucket.bucket
    
  • 网站配置路径错误:
    index_document.suffix和error_document.key应对应文件在Bucket中的key值,而非本地路径。若上传后文件key为index.html和404.html,需修改为:

    index_document {
      suffix = "index.html"
    }
    
    error_document {
      key = "404.html"
    }
    

内容的提问来源于stack exchange,提问作者charles uneze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:35:20