Skip to main content
Knowledge Base

Is there a way to inject variables into a Terraform apply run from another process outside of Terraform?

Answer

Is there a way to inject variables into Terraform from another process outside of Terraform? For example: I'm running an automated test where at some point I'm creating an AMI. I want to pass this AMI ID as a var in Terraform running in a CI / CD pipeline, so that I can have Terraform spin up that image.

Most likely you'll need to set a variable in Terraform using one of the [standard ways of assigning values to root module variables](https://www.terraform.io/docs/language/values/variables.html#assigning-values-to-root-module-variables). If you're using Terragrunt, you would write the value to a `terragrunt.hcl` file. Some programmatic options: - If you are doing this for testing, then we have terratest where you can use Go to dynamically generate variables and drive terraform apply. Examples of this are at [terratest.gruntwork.io](http://terratest.gruntwork.io/) **(Open source: no subscription needed)** - If you want to do a CI/CD workflow where you are updating variables to commit to git, then we have `terraform-update-variable`, which is a bash script that can update a `tfvars` or `terragrunt.hcl` file and commit the update to git: https://github.com/gruntwork-io/terraform-aws-ci/tree/master/modules/terraform-helpers **(Subscriber only)** - If you want to dynamically update variables every time you run `terraform`, then [Terragrunt](https://terragrunt.gruntwork.io) offers the `run_cmd` function which can run arbitrary commands to render out to the Terraform variable every time `terraform` is called. Example is here: https://terragrunt.gruntwork.io/docs/reference/built-in-functions/#run_cmd **(Open source: no subscription needed)**