chapter twelve

12 Terraform in Automation

 

This chapter covers:

  • Designing workflows for running Terraform at scale
  • Developing a CI/CD pipeline for automating Terraform deployments
  • Generating Terraform configuration code
  • Toggling dynamic blocks with a conditional expression

If you are struggling with how to run Terraform at scale, rest easy friend, because this chapter is for you. Until now, I have assumed you are deploying Terraform from your local machine. This is a reasonable assumption for individuals and even small teams (as long as you are using a remote state backend). Large teams and organizations with many individual contributors, on the other hand, would benefit from running Terraform in automation.

As you may recall from chapter 6, HashiCorp already has two products designed for running Terraform in automation: Terraform Cloud and Terraform Enterprise. They are basically the same product; Terraform Cloud is just the managed SaaS offering of Terraform Enterprise. In this chapter we will develop a CI/CD pipeline for deploying Terraform workspaces in automation, modeled after the design of Terraform Enterprise. The stages of the CI/CD pipeline are shown in figure 12.1.

Figure 12.1 A CI/CD pipeline for Terraform deployments with four stages. Changes to configuration code stored in a VCS source repository triggers a “terraform plan” to be run. If the plan succeeds, a manual approval is required before the changes are applied into production.

12.1  Poor Man’s Terraform Enterprise

12.1.1    Reverse Engineering Terraform Enterprise

12.1.2    Detailed Engineering

12.2  Beginning at the Root

12.2.1    Writing the Module Wrapper Code

12.3  Developing a Terraform CI/CD Pipeline

12.3.1    Configuring Input Variables

12.3.3    Building the Plan and Apply Stages

12.3.4    Configuring Environment Variables

12.3.5    Declaring the Pipeline as Code

12.3.6    Touching Base

12.3.7    Deploying to AWS

12.4  Testing Automated Terraform Workflows

12.4.1    Creating a Source Repository

12.4.2    Queuing a Destroy Run

12.5  Fireside Chat

12.5.1    FAQ

12.6  Summary