Terraform Best Practices

Hi there! I’m trying to set up a pipeline for a repository to begin using Terraform.

Are there any well defined best practices around this process? Specifically, I want to accomplish the following:

  • A terraform init and terraform plan as the first step. In my pipeline.yml file, I’m switching to the directory and running those two commands (along with validate). I’m using an artifact path of the terraform/ directory where all Terraform code is stored for all repositories and providing the -out plan.tf flag to terraform plan.

For a given pull request, I only want these steps to run. When the PR is merged to master, I’d like to run another pipeline that is identical but then adds the terraform apply step - I’d like to use the “apply to production” button at this step to require manual unblocking so that someone has time to review the plan output again prior to the apply step.

Does this require two different pipelines? What’s the best way to handle running the additional step after the PR is merged? My current pipeline as I conceptualize this so far:

steps:
  - label: ":terraform: :thinking_face: planning"
    commands: |
      cd terraform
      terraform validate
      terraform init
      terraform plan -out plan.tf
    artifact_paths:
      - "terraform/*"
    concurrency: 1
    concurrency_group: foobar/ops/terraform

Would I simply need another pipeline with the additional step? I guess I’m really just trying to make sure I’m sectioning this off properly and asking for intervention in the right place.

Thanks for any clarification!

I think to start I would review this great doc about running terraform within CI. It explains all the extra command line arguments you should use: https://learn.hashicorp.com/terraform/development/running-terraform-in-automation

You don’t need two different pipelines, you can tell buildkite to only run certain steps on certain branch builds. If you add the attribute branches: master to any command step, this step will only run on master builds.