Last active
November 28, 2024 14:24
-
-
Save sjovang/5a5d82af2e5396db28c99ef5608732ef to your computer and use it in GitHub Desktop.
Run terraform plan and apply, upload the plan artifact to job artifacts and display the changes in GitHub's job summary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Apply Terraform configuration | |
on: | |
push: | |
branches: | |
- main | |
permissions: | |
id-token: write | |
contents: read | |
jobs: | |
apply: | |
name: 'Apply Terraform configuration' | |
runs-on: ubuntu-latest | |
environment: production | |
steps: | |
- name: Checkout repository | |
uses: actions/checkout@v4 | |
- name: Setup Terraform | |
uses: hashicorp/setup-terraform@v3 | |
- name: Initialize Terraform | |
run: terraform init | |
- name: Plan | |
run: | | |
terraform plan -no-color -input=false -lock-timeout=60s -out=tfplan | |
terraform show -json -no-color tfplan > tfplan.json | |
id: plan | |
- name: Save terraform plan to artifacts | |
uses: actions/upload-artifact@v4 | |
with: | |
name: 'terraform plan' | |
path: tfplan | |
- name: Setup Python | |
uses: actions/setup-python@v5 | |
with: | |
cache: 'pip' | |
python-version: '3.13' | |
- name: Install python dependencies | |
run: pip install -r requirements.txt | |
- name: Parse terraform plan | |
shell: python | |
id: parseplan | |
run: | | |
import json | |
import os | |
import pandas as pd | |
with open('tfplan.json') as f: | |
data = json.load(f) | |
df = pd.json_normalize(data['resource_changes']).fillna(0) | |
df.columns = df.columns.str.replace(".", "_") | |
df['action'] = [','.join(map(str, l)) for l in df['change_actions']] | |
df_filtered = df[df['action'].str.contains('no-op') == False] | |
try: | |
if df_filtered.shape[0] > 0: | |
markdown_output=df_filtered[["address", "action"]].to_markdown(index=False) | |
with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as gh_summary: | |
gh_summary.write('### Overview of changes from terraform plan\n\n') | |
gh_summary.write(markdown_output) | |
except: | |
raise | |
- name: Apply changes | |
run: terraform apply -input=false -no-color -lock-timeout=60s -auto-approve tfplan |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment