'How to integrate terraform state into github action workflow?
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 }}"
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark B |
Solution 2 | Dustin |