We are deploying resources with Terraform from Azure DevOps.
In a Terraform main.tf file, it is recommended to use variables. The advantages are numerous: reusability, centralized configuration, simplified maintenance, increased flexibility, and improved security by separating sensitive data from the code…
One way to do this is to directly list these variables as parameters in the “terraform plan” command line. For example:
terraform plan -var myVar="var_value" -out main.tfplan
However, there is a limit to the number of variables that can be listed in the command line. Fortunately, to avoid this limitation and simplify the management of these variables, they can be stored in a dedicated file and referenced in the command line:
terraform plan -var-file terraform.tfvars -out main.tfplan
You can assign values to these variables directly in this file. However, modifying their values will require a change in the code of our repository, which we want to avoid. The solution to avoid this is as follows: link these Terraform variables to DevOps variables, either in a pipeline or in a variable group. Here’s how to do that.
First, we need to store this variables file, which we will call “terraform.tfvars”, in the repository with the other Terraform files, in a dedicated folder:
In this file, we need to link the Terraform variables to DevOps variables. To make it easier to understand and maintain, we assign the same name to the DevOps variables:
In our Build pipeline, we need two tasks to generate the output artifact that will serve as input for the Release pipeline:
- task: CopyFiles@2 displayName: "Copy Files to: terraform" inputs: SourceFolder: HR/Terraform TargetFolder: "$(build.artifactstagingdirectory)/terraform" - task: PublishPipelineArtifact@1 displayName: "Publish Pipeline Artifact : terraform" inputs: targetPath: "$(build.artifactstagingdirectory)/terraform" artifact: terraform
We can then view our variables file in the generated artifacts:
In the Release pipeline, a task must be executed beforehand, prior to the Terraform instructions.
Indeed, we must inform the process that the DevOps variables should be interpreted as such in the file. The task that allows this is the “Replace tokens” task, configured with the correct token pattern used in the file. In our case, $( … ):
Then, don’t forget two things:
All your Terraform variable management is now handled in DevOps.