Search code examples
terraformgithub-actionsterraform-provider-azure

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 repo layout: enter image description here

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

  • 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.