Backup Terraform state in B2 #12
This file contains 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: Terraform | |
on: | |
push: | |
branches: [main] | |
pull_request: | |
jobs: | |
run: | |
name: Run | |
runs-on: ubuntu-22.04 | |
permissions: | |
contents: read | |
pull-requests: write | |
env: | |
TF_HTTP_PASSWORD: ${{ github.token }} | |
TF_IN_AUTOMATION: "true" | |
steps: | |
- name: Checkout | |
uses: actions/checkout@v3 | |
- uses: hashicorp/setup-terraform@v3 | |
with: | |
terraform_version: "1.6.6" | |
- run: terraform init | |
- run: terraform plan -out=tfplan | |
- run: terraform apply tfplan | |
if: ${{ github.event_name == 'push' && github.ref_name == 'main' }} | |
- name: Backup state | |
env: | |
AWS_ACCESS_KEY_ID: ${{ secrets.B2_TFBACKUP_KEY_ID }} | |
AWS_SECRET_ACCESS_KEY: ${{ secrets.B2_TFBACKUP_SECRET_KEY }} | |
AWS_DEFAULT_REGION: us-east-1 | |
AWS_ENDPOINT_URL: https://s3.us-east-005.backblazeb2.com | |
run: | | |
terraform show -json > state.json | |
aws s3 cp state.json s3://terraform-state-backup/${{ github.repository }}/${date +%s}.json | |
- run: terraform show -no-color tfplan > summary.txt | |
if: ${{ github.event_name == 'pull_request' }} | |
- name: Show plan on PR | |
uses: actions/github-script@v7 | |
if: ${{ github.event_name == 'pull_request' }} | |
with: | |
github-token: ${{ github.token }} | |
script: | | |
const { repository: { pullRequest: { comments } } } = await github.graphql(` | |
query($owner:String!, $name:String!, $pr:Int!) { | |
repository(owner:$owner, name:$name) { | |
pullRequest(number:$pr) { | |
comments(last: 10) { | |
nodes { | |
id, | |
minimizedReason | |
author { | |
...on Bot { | |
login | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
`, { | |
owner: context.repo.owner, | |
name: context.repo.repo, | |
pr: context.issue.number, | |
}) | |
const commentsToHide = comments.nodes.filter((comment) => { | |
return !comment.minimizedReason && comment.author.login == "github-actions" | |
}) | |
console.log({ commentsToHide }) | |
await github.graphql(` | |
mutation { | |
${commentsToHide.map((c,i) => | |
`c${i}: minimizeComment(input: { subjectId: "${c.id}", classifier: OUTDATED }) { | |
clientMutationId | |
} | |
` | |
).join("")} | |
} | |
`) | |
const fs = require('fs').promises | |
const plan = await fs.readFile('summary.txt', 'utf-8') | |
const codefence = "```" | |
const body = ` | |
🏗️ Terraform Plan | |
${codefence} | |
${plan.trim("\n")} | |
${codefence}` | |
github.rest.issues.createComment({ | |
issue_number: context.issue.number, | |
owner: context.repo.owner, | |
repo: context.repo.repo, | |
body, | |
}) |