这是一个仅计算的Terraform模块(即,一个不会制作任何远程API调用的模块),该模块收集了特定基本目录下的所有文件,并渲染具有特定后缀作为Terraform模板文件的文件。
module "template_files" {
source = " hashicorp/dir/template "
base_dir = " ${ path . module } /src "
template_vars = {
# Pass in any values that you wish to use in your templates.
vpc_id = " vpc-abc123 "
}
} files输出是从文件路径相对于基本目录到具有以下属性的对象的映射:
content_type :用于文件的MIME类型。content :渲染模板后,文件的字面内容。source_path :非网板文件的本地文件系统位置。digests :包含将各种摘要/哈希算法应用于文件内容的结果。 content和source_path是相互排斥的。 content设置为模板文件,并包含渲染模板的结果。对于非template文件, source_path设置为本地磁盘上文件的位置,该文件避免尝试将非UTF-8文件(例如图像)(例如图像)加载到内存中。
每个文件的digests映射包含以下键,其值是将命名的哈希函数应用于文件内容的结果:
md5sha1sha256base64sha256base512base64sha512默认情况下,文件名以.tmpl结尾的基本目录中的任何文件都解释为模板。您可以通过将变量template_file_suffix设置为以一段时间开头的字符串,然后是一个或多个非期限字符来覆盖后缀。
模板被解释为Terraform的字符串模板语法。模板可以使用Terraform的任何内置功能,除了templatefile函数,该功能是该模块内部用于模板渲染的内容。
任何没有模板文件后缀的文件都将被视为静态文件,将本地路径返回到源文件。
根据所有发现的文件的后缀选择内容类型值(结果对象中的content_type )。
变量file_types是从文件名后缀(点,至少一个非点字符)到Content-Type标题值的映射。默认映射包括许多在静态网站上使用的FILETYPE。
如果模块遇到根本没有后缀或后缀不在file_types中的文件,则它将使用可变default_file_type的值作为后备,该值本身将默认为application/octet-stream 。
该模块的关键用例是生产内容以上传到Amazon S3存储桶中,例如用作静态网站。
在您的调用模块中,使用for_each从AWS提供商中使用aws_s3_bucket_object为每个文件创建一个S3对象:
resource "aws_s3_bucket_object" "static_files" {
for_each = module . template_files . files
bucket = " example "
key = each . key
content_type = each . value . content_type
# The template_files module guarantees that only one of these two attributes
# will be set for each file, depending on whether it is an in-memory template
# rendering result or a static file on disk.
source = each . value . source_path
content = each . value . content
# Unless the bucket has encryption enabled, the ETag of each object is an
# MD5 hash of that object.
etag = each . value . digests . md5
}将文件上传到GCS的模式与上面的Amazon S3非常相似:
resource "google_storage_bucket_object" "picture" {
for_each = module . template_files . files
bucket = " example "
name = each . key
content_type = each . value . content_type
# The template_files module guarantees that only one of these two attributes
# will be set for each file, depending on whether it is an in-memory template
# rendering result or a static file on disk.
source = each . value . source_path
content = each . value . content
}该模块需要Terraform V0.12.8或更高版本。它不使用任何Terraform提供商,也不会宣布任何地Terraform资源。
template_dir资源类型? template_dir资源类型是作为务实的解决方法实现的,用于早期版本的Terraform中的各种限制,但它是有问题的,因为它违反了假设Terraform对资源的构成:它修改了Terraform在系统中运行的本地状态,因此,它的结果是,因此在其他主机上运行Terraform时,资源不可见。
对于大多数用例,Terraform 0.12.8不再需要template_dir资源类型,因为有足够的内置功能可以在没有资源的情况下获得类似的结果。
除了该模块是Terraform工作流程中比template_file资源更好的公民外,它还允许在同一目录中混合模板和非转换文件的混合物,并且只会加载到内存中并渲染模板文件。对于非模板文件,它只会将它们留在磁盘上,然后将本地文件系统路径返回到原始位置。
另一方面,该模块确实假定其结果将与其他资源类型一起使用,这些类型能够处理某些文件在内存中渲染的字符串,而直接从磁盘读取的其他文件。对于aws_s3_bucket_object是正确的,但是对于所有可能与任意文件一起使用的资源类型的资源类型都不正确。