CI/CD · Ship safely, repeatedly

How do you run infrastructure as code from CI?

Mediuminfrastructure as codeterraformciUpdated Oct 2026
Quiz this track

Short answer

Run a plan on pull requests and apply only after merge or approval, using locked remote state and least-privilege credentials. Review the plan output, detect drift, and keep infrastructure changes in the same review flow as code.

Infrastructure as code turns environment changes into reviewable diffs. CI adds consistency: the same tool version and the same plan are produced every time, rather than relying on an engineer laptop.

  • Plan on pull requests and publish the diff for review
  • Apply from a trusted branch or protected environment, not from fork pull requests
  • Use remote state with locking so concurrent runs cannot corrupt it
  • Scope cloud credentials to the specific stack and environment
  • Run drift detection on a schedule and reconcile deliberately
  • Pin provider and tool versions for reproducible plans
yaml
plan:
  stage: validate
  script:
    - terraform init
    - terraform validate
    - terraform plan -out=tfplan
  artifacts:
    paths:
      - tfplan

apply:
  stage: deploy
  when: manual
  script:
    - terraform apply tfplan
A saved plan can become stale if the state changes before apply. Treat apply failures and stale plans as signals to re-plan, not as reasons to force through the old plan.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why is remote state locking important?
  2. 2How do you prevent a fork pull request from applying infrastructure?
  3. 3What is infrastructure drift?
  4. 4How do you review a large terraform plan?

Say it in the interview

I run plan on pull requests so the infrastructure diff is reviewed like code, and apply only from a protected branch or approved environment. State is remote and locked, credentials are scoped to the stack, and tool versions are pinned. I also run scheduled drift detection. A saved plan is convenient but must be re-planned if state changed, otherwise the apply may not match what was reviewed.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live CI/CD mock interview and get scored feedback on depth, clarity and confidence.