Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Can we use the repo variables inside the terraform code by referring them as a environment variables

salluri December 8, 2021

I am trying to refer the repo variables inside my terraform code as shown below 

export AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID

Is this the actual way to declare or is there any other way to declare the variables in the code?

1 answer

2 votes
Patrik S
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
December 9, 2021

Hello @salluri

Welcome to Atlassian Community!

Bitbucket Pipelines allows you add, edit, or remove variables at the account, repository, and deployment environment levels. These are called user-variables, and along with the default variables, they are configured as environment variables in the build container of each of your pipeline's steps.

You can reference those variables in your bitbucket-pipelines.yml file or in any script you invoke using the following syntax :

$MY_BITBUCKET_VARIABLE_NAME

 However, each programming/configuration language has it's own way of fetching the value from an environment variable. For this particular case, where you are using Terraform, looking at their documentation about using environment variables, I've found the following :

  • Each input variable accepted by a module must be declared using a variable block:
    variable "aws_code_access_key" {
      type = string
    }

     

  • Terraform searches the environment of its own process for environment variables named TF_VAR_ followed by the name of a declared variable. For the example variable above, on your build script you would have to set a environment variable named TF_VAR_aws_code_access_key using the value of the pipeline variable $MY_BITBUCKET_VARIABLE_NAME, like this:
    $ export TF_VAR_aws_code_access_key=$MY_BITBUCKET_VARIABLE_NAME
    $ terraform plan

     

  • Within the module that declared a variable, its value can be accessed from within expressions as var.<NAME>, where <NAME> matches the label given in the declaration block:
    resource "aws_instance" "example" {
      instance_type = "t2.micro"
      access_key           = var.aws_code_access_key
    }

The information above was extracted from the official terraform documentation. For more details on how terraform references environment variables you can check the following link:

Hope that helps to address your questions! Let us know if you need further assistance.

Thanks you!

Best regards,

Patrik S

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
TAGS
AUG Leaders

Atlassian Community Events