如何通过Terraform排除infra目录,将React应用上传至AWS S3?
解决Terraform上传React应用到S3时排除infra目录的问题
核心思路
通过Terraform的列表推导式配合路径判断,过滤掉infra目录下的所有文件,只上传React应用的业务代码和资源文件。
修改后的Terraform代码
resource "aws_s3_bucket_object" "react_app_files" { for_each = toset([ for file in fileset("../../ReactApp", "**") : file if !startswith(file, "infra/") ]) bucket = aws_s3_bucket.react_app.id key = each.value source = "../../ReactApp/${each.value}" # 保留你原有的其他配置,比如: # acl = "public-read" # content_type = mime_type("../../ReactApp/${each.value}") }
代码说明
fileset("../../ReactApp", "**"):遍历React根目录下所有文件及子目录的路径if !startswith(file, "infra/"):过滤掉所有以infra/开头的路径,彻底排除infra目录下的所有内容toset():把过滤后的路径列表转为集合,满足for_each的使用要求
如果后续需要排除其他目录,直接在if条件里追加判断即可,比如:
if !startswith(file, "infra/") && !startswith(file, "temp/")
内容的提问来源于stack exchange,提问作者jkhan_prog
相关产品推荐
相关产品推荐

