12 Automating Terraform

 

This chapter covers:

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

If you want to know how to run Terraform in automation, 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. On the other hand, large teams and organizations with many individual contributors, may benefit from automating Terraform

In chapter 6 we discussed how HashiCorp has two products for running Terraform in automation, these are: Terraform Cloud and Terraform Enterprise. Both of these products are basically the same; Terraform Cloud is simply the SaaS version 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 trigger 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    Design Details

12.2  Beginning at the Root

12.3  Developing a Terraform CI/CD Pipeline

12.3.1    Declaring Input Variables

12.3.2    IAM Roles and Policies

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.4  Deploying a Terraform CI/CD Pipeline

12.4.1    Creating a Source Repository

12.4.2    Creating a Least Priviliged Deployment Policy

12.4.3    Configuring Terraform Variables

12.4.4    Deploying to AWS

12.4.5    Connecting to GitHub

12.5  Deploying “Hello World!” with the Pipeline

12.5.1    Queuing a Destroy Run

12.6  Fireside Chat

12.6.1    FAQ

12.7  Summary