Terraform 可以使用 bash 环境变量吗? [英] Can Terraform use bash environment variables?

查看:25
本文介绍了Terraform 可以使用 bash 环境变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 terraform 中定义 aws 提供程序时,

When defining the aws provider in terraform,

provider "aws" {
    access_key = "<AWS_ACCESS_KEY>"
    secret_key = "<AWS_SECRET_KEY>"
    region = "<AWS_REGION>"
}

我希望能够只使用已定义的系统变量

I'd like to be able to just use the, already defined, system variables

AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY

有没有办法让 tf 文件读取环境变量?做类似的事情,

Is there any way to have the tf files read environment variables? doing something like,

provider "aws" {
    access_key = env.AWS_ACCESS_KEY_ID
    secret_key = env.AWS_SECRET_KEY_ID
    region = env.AWS_REGION
}

推荐答案

可以,可以读取 Terraform 中的环境变量.有一种非常具体的方法可以做到这一点.您需要将环境变量设为 terraform 中的变量.

Yes, can read environment variables in Terraform. There is a very specific way that this has to be done. You will need to make the environment variable a variable in terraform.

例如,我想将 super_secret_variable 传递给 terraform.我需要在我的 terraform 文件中为其创建一个变量.

For example I want to pass in a super_secret_variable to terraform. I will need to create a variable for it in my terraform file.

variable "super_secret_variable" {
    type = "string
}

然后根据惯例,我必须像这样在我的环境变量前面加上 TF_VAR_:

Then based on convention I will have to prefix my environment variable with TF_VAR_ like this:

TF_VAR_super_secret_variable

然后 terraform 会自动检测并使用它.基于特定顺序的 Terraform 处理器变量,顺序是 -var 选项、-var-file 选项、环境变量,然后是默认值(如果在 tf 文件中定义).

Then terraform will automatically detect it and use it. Terraform processors variables based on a specific order that order is -var option, -var-file option, environment variable, then default values if defined in your tf file.

您也可以通过 CLI 传入环境变量,像这样在 terraform 中设置变量.

Alternative you can pass environment variables in through the CLI to set variables in terraform like so.

> terraform apply -var super_secret_variable=$super_secret_variable

这不需要您在其前面加上前缀,因此如果它们是您无法更改的,那么这可能是您最好的做法.

This doesn't require that you prefix it so if they are something you can't change that may be your best course of action.

您可以在文档中阅读更多此处.

You can read more here in the docs.

这篇关于Terraform 可以使用 bash 环境变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆