If you want to create an infrastructure CI/CD pipeline for AWS using Terraform, you want to keep the state in a remote backend. When provisioning an environment with Terraform that includes the state backend resources, you will need two actions to set up the remote state backend. In this blog I will present you with a CloudFormation template with which you can bootstrap the AWS account. This will decouple the state backend resources from the Terraform template. This allows you to use the remote backend straight away from your CI/CD pipeline.
When provisioning an environment with Terraform that includes the state backend resources, you will need two actions to set up the remote state backend. First you have to provision the environment with the state backend resources. Next, You then add the state backend configuration and copy the local state to the remote state. This means you cannot run the first
terraform apply from your CI/CD pipeline.
To solve this problem you can decouple the state backend from the Terraform template. This can be done by an AWS CloudFormation template for bootstrapping the AWS account. The template consists of a S3 Bucket, Replication bucket and a DynamoDB table. After bootstrapping, Terraform will be able to push the state to the remote backend on the first run. This can be helpful when running Terraform from a CD/CD pipeline for the first time without having to move the state around.
The following CloudFormation template solves the problem as it creates all the resources shown in the following diagram:
- S3 server-side encryption at rest
- S3 bucket versioning
- DynamoDB server-side encryption
- Multi region support for bucket replication
- All public access is blocked
- No cross-account support
In this blog I presented you with a CloudFormation template which you can use to bootstrap a new AWS account with a state backend. By applying the template when creating the AWS account, no manual steps are required to (re)deploy your infrastructure using Terraform.