Skip to content

Instantly share code, notes, and snippets.

@tboeghk
Last active February 17, 2023 10:27
Show Gist options
  • Save tboeghk/0b8defc1d12c84bc2ed8964cb57aedde to your computer and use it in GitHub Desktop.
Save tboeghk/0b8defc1d12c84bc2ed8964cb57aedde to your computer and use it in GitHub Desktop.
Terraform state drift detection in GitHub Actions
name: terraform state drift detection
# Execute this action on push to main and everyday at 7am
on:
push:
branches:
- main
workflow_dispatch:
schedule:
- cron: '0 7 * * *'
jobs:
build:
runs-on: ubuntu-latest
steps:
# (1) set up workspace, Terraform and
# supply credentials needed for the
# Terraform plan (DigitalOcean token)
- uses: actions/checkout@v3
- uses: hashicorp/setup-terraform@v2
with:
cli_config_credentials_token: ${{ secrets.TERRAFORM_CLOUD_API_TOKEN }}
- name: prepare-credentials
run: |
cat << EOF > secrets.auto.tfvars
do_token = "${{ secrets.DO_TOKEN_RO }}"
EOF
# (2) Terraform init and validate
- id: init
run: terraform init -no-color -input=false -lock=false
- id: validate
run: terraform validate -no-color
# (3) Execute Terraform plan and add plan to the build summary
- id: plan
run: terraform plan -no-color -lock=false -detailed-exitcode -compact-warnings
continue-on-error: true
- run: |
cat << 'EOF' >> $GITHUB_STEP_SUMMARY
### 🤖 Terraform plan
```terraform
${{ steps.plan.outputs.stdout }}
```
EOF
# (4) Upon Terraform state drift, notify slack and fail build
- name: Slack Notification
uses: rtCamp/action-slack-notify@v2
if: ${{ steps.plan.outputs.exitcode > 0 }}
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK_URL }}
SLACK_COLOR: failure
SLACK_TITLE: Terraform state drift detected
SLACK_MESSAGE: ":robot: Please check plan for workspace `locations`"
SLACK_FOOTER: "${{ github.repository }}"
- name: Fail job on plan changes
if: ${{ steps.plan.outputs.exitcode > 0 }}
uses: actions/github-script@v6
with:
script: |
core.setFailed('Terraform state drift detected')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment