如何在 terraform 的 file() 中传递变量

Jat*_*hal -2 variables file terraform terraform-provider-aws

需要使用 terraform 创建 cloudfront 公钥,这里公钥是根据环境单独的,并以 {env_name}.pem 形式存储在目录名称 public-key-cf 中。env_name 可以是 dev、stage、prod。

为了实现这一点,使用了以下 terraform 块:

resource "aws_cloudfront_public_key" "documents-signing-key" {
  name        = "cf-public-key"
  comment     = "Public Key"
  encoded_key = file("${path.module}/public-key-cf/"${var.environment}".pem)"
}
Run Code Online (Sandbox Code Playgroud)

我收到错误如下:

This character is not used within the language.
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

谢谢。

小智 5

您的代码中似乎存在语法问题,并且在错误的位置使用了引号。请参阅字符串模板以了解 terraform 中的字符串插值。

\n
    \n
  • 这是我用来模拟您的查询的结构。
  • \n
\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 dependencies.tf\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 file_function_variable.tf\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.tf\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 public-key-cf\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 dev.pub\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • 其中 file_function_variable.tf 是我们最关注的地方。
  • \n
\n
\n## File function within a sting input (multiple string interpolation).\nresource "aws_security_group" "file_function_variable" {\n  name        = "allow_tls"\n  description = "Allow TLS inbound traffic with ${file("${path.module}/public-key-cf/${var.environment}.pub")}"\n  vpc_id      = local.vpc_id\n\n  tags = {\n    Name = "allow_tls"\n  }\n}\n\n## usage of explicit file function.\nresource "aws_cloudfront_public_key" "documents-signing-key" {\n  name        = "cf-public-key"\n  comment     = "Public Key"\n  encoded_key = file("${path.module}/public-key-cf/${var.environment}.pub")\n}\n\nvariable "environment" {\n  type        = string\n  description = "(optional) Environment for the deployment"\n  default     = "dev"\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • 上面的代码生成了下面的计划,以验证它的外观。
  • \n
\n
\n## File function within a sting input (multiple string interpolation).\nresource "aws_security_group" "file_function_variable" {\n  name        = "allow_tls"\n  description = "Allow TLS inbound traffic with ${file("${path.module}/public-key-cf/${var.environment}.pub")}"\n  vpc_id      = local.vpc_id\n\n  tags = {\n    Name = "allow_tls"\n  }\n}\n\n## usage of explicit file function.\nresource "aws_cloudfront_public_key" "documents-signing-key" {\n  name        = "cf-public-key"\n  comment     = "Public Key"\n  encoded_key = file("${path.module}/public-key-cf/${var.environment}.pub")\n}\n\nvariable "environment" {\n  type        = string\n  description = "(optional) Environment for the deployment"\n  default     = "dev"\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

结论:

\n

正如另一个答案中提到的,在使用 terraform 时最好使用插件/扩展。\n对于 VSCode,有一个官方的HashiCorp.terraform插件,它支持语法突出显示等。

\n