Reputation: 6657
I have the github action workflow outlining the simple process of spinning up terraform to create resources in Azure. What I am missing is how to integrate the terraform state file so that upon sequential runs of this workflow it should compare the current state with the main.tf file and only permit the net changes. At present if I run this sequentially, will always fail the second time because the resources will have already been created in Azure.
How can I configure the github workflow below to permit terraform state file comparison?, I have not found a single source that does this
github action workflow:
name: Terraform deploy to Azur
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: "Checkout"
uses: actions/checkout@master
- name: "Terraform Init"
uses: hashicorp/terraform-github-actions@master
with:
tf_actions_version: 0.12.13
tf_actions_subcommand: "init"
- name: "Terraform Plan"
uses: hashicorp/terraform-github-actions@master
with:
tf_actions_version: 0.12.13
tf_actions_subcommand: "plan"
args: -var="client_secret=${{ secrets.clientSecret }}"
-var="client_id=${{ secrets.clientId }}"
-var="tenant_id=${{ secrets.tenantId }}"
-var="sub=${{ secrets.sub }}"
- name: "Terraform Apply"
uses: hashicorp/terraform-github-actions@master
with:
tf_actions_version: 0.12.13
tf_actions_subcommand: "apply"
args: -var="client_secret=${{ secrets.clientSecret }}"
-var="client_id=${{ secrets.clientId }}"
-var="tenant_id=${{ secrets.tenantId }}"
-var="sub=${{ secrets.sub }}"
Upvotes: 9
Views: 13865
Reputation: 1033
If you are using Terraform cloud then this is what I've done
workspaces { name = "dev" }
hostname = "app.terraform.io"
organization = "terraform-cloud-orgid"
backend.tf
with following contents//Donot uncomment this file. This file will be uncommented only in Github Actions
#terraform {
# backend "remote" {}
#}
- name: Uncomment Terraform Cloud Backend Configuration file
id: uncomment
run: sed -i 's/^#*//' backend.tf
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: 1.1.0
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
- name: Terraform Init
id: init
run: terraform init -backend-config=dev.hcl
Upvotes: 0
Reputation: 129
A better solution than storing the backend configuration elsewhere, when running in a pipeline, is to generate the backend configuration on the fly just before the terraform init
:
- name: Setup Terraform Backend
id: backend
run: |
cat > backend.tf << EOF
terraform {
backend "remote" {
organization = "${secrets.TF_CLOUD_ORGANIZATION}"
workspaces {
name = "${secrets.TF_CLOUD_WORKSPACE}"
}
}
}
EOF
- name: Terraform Init
id: init
run: terraform init
Upvotes: 3
Reputation: 200562
You need to add a backend configuration to your Terraform so it will store the state file somewhere externally, that it can reference and update on each run.
Upvotes: 8