Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure environment variables in Hashicorp Terraform

I'm quite new to Terraform, though I have gone through all of the instructional modules available on Hashicorp's site.

Currently, I'm struggling with understanding how to set up environment variables. I know how to reference variables in the main.tf config (access_key = "${var.access_key}"), and I know how to save that access key to a separate file and reference that, but what I don't understand (and can't find any documentation/instruction on) is how to set up environment variables so I don't have to save the access key to a file.

Does anyone know how best to go about doing this?

like image 995
Neal Avatar asked Mar 07 '19 20:03

Neal


People also ask

Can Terraform access environment variables?

Terraform can directly access environment variables that are named using the pattern TF_VAR_ , for example TF_VAR_foo=bar will provide the value bar to the variable declared using variable "foo" {} .


1 Answers

Terraform can infer the following environment variables for AWS

export AWS_ACCESS_KEY_ID="anaccesskey"
export AWS_SECRET_ACCESS_KEY="asecretkey"

Ref: https://www.terraform.io/docs/providers/aws/#environment-variables

But I would suggest trying the AWS Profile. You can add credentials to ~/.aws/credentials file like

[myprofile]
aws_access_key_id     = anaccesskey
aws_secret_access_key = asecretkey

and then you can set environment variable export AWS_PROFILE=myprofile. Now, if you run terraform from this shell, it should pick credentials listed under myprofile.

Also, you can have you AWS Provider code as follows:

provider "aws" {
  profile = "myprofile"
  region  = "${var.region}"
}

In my experience, interacting with AWS using profile is easy and better than setting environment variables on each shell.

You can refer an example here https://github.com/pradeepbhadani/tf-examples/blob/master/ex2/provider.tf

Hope this helps.

like image 139
pradeep Avatar answered Oct 13 '22 05:10

pradeep