OpenTofu in CI/CD & securing state
Automate apply; protect state & supply chain.
The safe automation pattern is the same one every mature Terraform shop uses, run with tofu: on a pull request, tofu plan and post the diff for review; on merge to main, tofu apply the reviewed plan — never an interactive apply from a laptop against production. The plan-on-PR / apply-on-merge split is what makes infra changes reviewable and auditable.
plan:image: ghcr.io/opentofu/opentofu:1.8script:- tofu init- tofu plan -out=tfplan.bin- tofu show -json tfplan.bin > plan.json- conftest test plan.json --policy policy/ # policy gateartifacts: { paths: [tfplan.bin] }apply:script: [tofu apply tfplan.bin] # apply the exact reviewed planrules: [{ if: '$CI_COMMIT_BRANCH == "main"' }]when: manual # human approval for prodenvironment: production
Securing the pipeline
Terraform/OpenTofu automation holds the keys to your entire cloud, so the pipeline is a top-tier target. Give CI short-lived cloud credentials via OIDC rather than static keys; protect the state backend and (better) turn on client-side state encryption so a compromised runner cannot read secrets from state; and commit the .terraform.lock.hcl so providers cannot be swapped underneath you. Apply the same least-privilege and protected-environment rules the CI/CD course covers.