Set values in variables of terraform.tfvars file with Jenkins params

Does anyone know how I can assign a value to a variable in the terraform.tfvars file that comes from a parameter configured in jenkins, I am doing the following in the terrraform.tfvars file:

location = “$ {params.location}”

this works i can use the params. in the jenkinsfile, but it doesn’t work in the terraform.tfvars to assign the value to the variable.

Thanks

You can use environment variables: Use Jenkins to set environment variables and have Terraform read those values.

Take a look at TF_VAR_name at

Thanks for your answer Javier, I did this but it works by calling the variable from the JenkinsFile but in terraform.tfvars it did not work or maybe I did not do it correctly, soon you have an example of how the variable should be parsed from the terraform. tfvars?

Here’s an example using declarative Jenkinsfile.

pipeline {
  environment {
    TF_VAR_location = ${params.location}
  }
}

If that doesn’t work you should be able to set it in a script {} block in one of your stages.

We prefer not to do this and instead check in our vars files for each env.

Then in the Jenkinsfile we run terraform -var-file=${BRANCH_NAME}.tfvars

Where the branch represents the environment.

Hi
Thanks kunickiaj this works to assign the value of the Jenkins parameter to the environment variable TF_VAR_location in the jenkinsfile, but how can I in the terrafomr.tfvars file set the variable location with the value that I now assign the value of TF_VAR_location:

in terraform.tfvars file variable location = TF_VAR_location

thanks

You don’t need to. Terraform will use the value in the env var as it takes precedence.

See the documentation reference @javierruizjimenez linked to for more info on where terraform will pick up variable values from and in what order.

Alternatively you can also set them explicitly on the command line with -var but I find environment variables more flexible. For example:

terraform -var location=${params.location} this will have the same effect as setting TF_VAR_location which has the same effect as editing the terraform.tfvars file.

@rrmartinez87 were you able to solve this issue ? if yes could you share an example ?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.