在Terraform配置中获取环境变量



我有两个环境变量。一个是CCD_ 1,另一个是CCD_。然后我有一个地形文件,看起来像这样。

resource "google_container_cluster" "primary" {
    name = "marcellus-wallace"
    zone = "us-central1-a"
    initial_node_count = 3
    master_auth {
        username = ${env.TF_VAR_UN}
        password = ${env.TF_VAR_PW}
    }
    node_config {
        oauth_scopes = [
            "https://www.googleapis.com/auth/compute",
            "https://www.googleapis.com/auth/devstorage.read_only",
            "https://www.googleapis.com/auth/logging.write",
            "https://www.googleapis.com/auth/monitoring"
        ]
    }
}

我想用环境变量TF_VAR_UNTF_VAR_PW替换的两个值是username和password。我尝试了上面显示的内容,但没有成功,我也尝试过其他一些东西,但总是遇到语法问题。

我会尝试更像这样的东西,它似乎更接近文档。

variable "UN" {
  type = string
}
variable "PW" {
  type = string
}
resource "google_container_cluster" "primary" {
  name = "marcellus-wallace"
  zone = "us-central1-a"
  initial_node_count = 3
  master_auth {
    username = var.UN
    password = var.PW
  }
  node_config {
    oauth_scopes = [
        "https://www.googleapis.com/auth/compute",
        "https://www.googleapis.com/auth/devstorage.read_only",
        "https://www.googleapis.com/auth/logging.write",
        "https://www.googleapis.com/auth/monitoring"
    ]
  }
}

CLI命令如下。

TF_VAR_UN=foo TF_VAR_PW=bar terraform apply

插值语法的使用会引发带有地形v0.12.18的警告。现在您不需要使用插值语法。您可以将其引用为var.hello

注意:从语言的角度来看,需要理解的一件重要事情是,不能使用环境变量来声明变量。只能使用环境变量为脚本中声明的变量赋值。例如,假设您有以下.tf脚本

variable "hello" { type=string }

现在,如果环境有一个变量TF_VAR_hello="foobar",那么在运行时,变量hello的值将为"foobar"。如果在没有声明变量的情况下分配变量,则不会产生任何效果。

您可以执行以下操作来实现此功能。

  1. 声明地形配置中要用作环境变量的变量
variable "db_password" { type= string } 
  1. 在要使用此变量的资源部分中,将其更改为
"db_password":"${var.db_password}"
  1. 导出环境变量
export TF_VAR_db_password="##password##"
  1. terraform planterraform apply

使用TF_VAR_UN0执行终端命令(读取环境变量),将输出重定向到文件,然后读取文件内容:

resource "null_resource" "read_environment_var_value_via_cli" {
  triggers = { always_run = "${timestamp()}" }
  provisioner "local-exec" {
    command = "echo $TF_VAR_UN > TF_VAR_UN.txt" # add gitignore
  }
}
data "local_file" "temp_file" {
  depends_on    = [ null_resource.read_environment_var_value_via_cli]
  filename      = "${path.module}/TF_VAR_UN.txt" 
}
# use value as desired
resource "google_container_cluster" "primary" {
    master_auth {
        username = data.local_file.temp_file.content # value of $TF_VAR_UN
        ..
    }
}

大多数提供商使用:

DefaultFunc:架构。EnvDefaultFunc("

  • https://github.com/terraform-providers/terraform-provider-infoblox/blob/master/infoblox/provider.go
  • https://github.com/terraform-providers/terraform-provider-openstack/blob/master/openstack/provider.go

或者,您可以使用bash:中的envsubst实用程序来替换文件本身中的变量

$ envsubst < main.tf > main.tf

或者使用带有变量的中间文件和输出上的最终配置:

$ envsubst < main.txt > main.tf

!必须使用export声明envsubst的变量:

$ export MYVAR=1729

源文件中的变量的格式必须为:$VARIABLE${VARIABLE}

为了使用需要包装的变量"例如:

username="${var.UN}"

最新更新