hashicorp / terraform

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
https://www.terraform.io/
Other
42.54k stars 9.52k forks source link

Allow TF to access environment variables, at least for the condition checks #31333

Open pszypowicz opened 2 years ago

pszypowicz commented 2 years ago

Current Terraform Version

Terraform v1.2.2

Use-cases

In the precondition I would like to check for the existing environment variables.

People are already depending heavily on the 'local-exec', this would allow better checks inside the terraform.

Proposal


resource "null_resource" "env" {

provisioner "local-exec" {
    command = "echo $TEST
}

lifecycle {
precondition {
condition = env_var(TEST) == "value"
error_message = "You have to setup environment variable to "value" to create this resource"
}
}
}
kmoe commented 2 years ago

Terraform does not have a function for accessing environment variables for the reasons described in https://github.com/hashicorp/terraform/issues/26477: however, you can use the TF_VAR_* convention to supply Terraform variables via environment variables. This will allow you to set the value of a variable which you can then use within your precondition.

pszypowicz commented 2 years ago

Thank you @kmoe for your response.

Not all variables are suitable to be kept in the TF state, as in this example: https://github.com/hashicorp/terraform-provider-kubernetes/issues/1753

Where I need to setup 2 environment variables:

AAD_SERVICE_PRINCIPAL_CLIENT_SECRET=$ARM_CLIENT_SECRET 
AAD_SERVICE_PRINCIPAL_CLIENT_ID=$ARM_CLIENT_ID

We already use environment variables outside of tfstate, for example for providers. My feature request is not a precedence here.

With a data provider (as in the ticket you linked), it means that the variable would then be stored in the TF state. The function would avoid that.

Preconditions are such a powerfull tool, that we could clearly take an advantage of that, for provisioners and so on.

ddaws commented 2 years ago

I don't think that Terraform should be able to read envvars like this because it's adds risk and changes the model for supplying parameters to Terraform. Currently values need to be explicitly passed to Terraform but by adding an env function like you suggest Terraform can grab information from the parent processes context. This could be used in supply chain attacks to steal credentials.