Terraform's life cycle in a CI/CD process
So far, we have seen and executed, on the local machine, the various Terraform commands that allow us to initialize, preview, apply, and destroy an infrastructure and to format and validate Terraform code. When using Terraform locally, in a development context, its execution life cycle is as follows:
The steps shown in the diagram follow this sequence:
- Code development
- Code formatting with terraform fmt
- Initialization with terraform init
- Code validation with terraform validate
- Planning with terraform plan
- Manual verification of Terraform changes on infrastructure
But IaC, like an application, must be deployed or executed in an automatic CI/CD process. It starts with the archiving of the Terraform code of the team members, triggers the CI, and executes the Terraform commands that we have studied in this chapter.
The following is a screenshot of the Terraform life cycle in CI/CD automation:
The steps of CI/CD by the CI server (in which Terraform is installed) for Terraform are as follows:
- Retrieving the code from the SCM
- Code formatting with terraform fmt
- Initialization with terraform init
- Code validation with terraform validate
- Display a preview of the infrastructure changes with terraform plan -out=out.tfplan
- Application of changes in automatic mode with terraform apply --auto-approve out.tfplan
By adding the --auto-approve option to the apply and destroy commands, Terraform can also be executed in automatic mode, so as not to ask for confirmation from the user to validate the changes that need to be applied. With this automation, Terraform can be integrated with CI/CD tools.
In the plan command, an out option is added to specify a file with the .tfplan format that corresponds to a file that contains the output of the plan command. This out.tfplan file is then used by the apply command. The advantage of this procedure is that it is possible to execute the application on a later plan, which can be used in a rollback case.
We have seen, in this section, that, apart from the usual Terraform commands of init, plan, apply, and destroy, Terraform also has options that will allow us to improve the readability of the code and validate the code syntax. We also explained that Terraform also allows a perfect integration into a CI/CD pipeline with a life cycle and automation options.
In the next section, we will see what the tfstate file is and how to protect it in a remote backend.