CI/CD with Terraform, GitHub, and Atlantis
local graph
Chapter 13 — CI/CD with Terraform, GitHub, and Atlantis
Section titled “Chapter 13 — CI/CD with Terraform, GitHub, and Atlantis”In this chapter, we are going to build on the previous chapters in this book by introducing pipelines for continuous integration (CI) and continuous deployment (CD). There are many CI and CD tools available for you, both open source and closed source, as well as self-hosted and Software-as-a-Service (SaaS). We are going to demonstrate an example pipeline, starting from committing source to the repository where we store Terraform code to applying changes in your infrastructure. We will do this automatically but with reviews from your team.
In this chapter, we are going to cover the following topics:
- What is CI/CD?
- Continuously integrating and deploying your infrastructure
- CI/CD with Atlantis
Technical requirements
Section titled “Technical requirements”For this chapter, you will need the following:
- A Linux box
- A free account on GitHub or similar platform (GitLab or Bitbucket)
- The latest version of Terraform
- The AWS CLI
- Git
What is CI/CD?
Section titled “What is CI/CD?”CI/CD is a set of practices, tools, and processes that allow software development teams to automate the building, testing, and deployment of their applications, enabling them to release software more frequently and with greater confidence in its quality.
Continuous integration (CI) is a practice where developers regularly integrate their code changes into a repository, and each integration triggers an automated build and test process. This helps catch errors early and ensures that the application can be built and tested reliably.
For example, using Docker, a developer can set up a CI pipeline that automatically builds and tests their application whenever changes are pushed to the code repository. The pipeline can include steps to build a Docker image, run automated tests, and publish the image to a Docker registry.
Continuous delivery is the practice of getting software to be available for deployment after the successful integration process. For example, with a Docker image, delivery would be pushing the image to the Docker registry from where it could be picked up by the deployment pipeline.
Finally, continuous deployment (CD) is the practice of automatically deploying continuous delivery process code artifacts (Docker images, Java JAR files, ZIP archives, and so on) to production as soon as they are tested and validated. This eliminates the need for manual intervention in the deployment process.
Let’s look at some common deployment strategies:
- Rolling deployment: This strategy involves deploying changes to a subset of servers at a time, gradually rolling out the changes to the entire infrastructure. This allows teams to monitor the changes and quickly roll back if any issues arise.
- Blue-green deployment: In this strategy, two identical production environments are set up, one active (blue) and the other inactive (green). Code changes are deployed to the inactive environment and tested before switching the traffic to the new environment. This allows for zero downtime deployment.
- Canary deployment: This strategy involves deploying changes to a small subset of users while keeping the majority of the users on the current version. This allows teams to monitor the changes and gather feedback before rolling out the changes to the entire user base.
- Feature toggles/feature switches: With this strategy, changes are deployed to production but hidden behind a feature toggle. This toggle is then gradually turned on for select users or environments, allowing teams to control the rollout of new features and gather feedback before making them available to everyone.
All of these strategies can be automated using CD tools, such as Jenkins, CircleCI, GitHub and GitLab Actions, Travis CI, and many others.
While we’re talking about the deployment of applications, we need to at least mention GitOps. GitOps is a new approach to infrastructure and application deployment that uses Git as the single source of truth for declarative infrastructure and application specifications. The idea is to define the desired state of the infrastructure and applications in Git repositories and use a GitOps tool to automatically apply those changes to the target environment.
In GitOps, every change to the infrastructure or application is made via a Git commit, which triggers a pipeline that applies the changes to the target environment. This provides a complete audit trail of all changes and ensures that the infrastructure is always in the desired state.
Some of the tools that help with enabling GitOps include the following:
- FluxCD: This is a popular GitOps tool that can automate the deployment and scaling of applications and infrastructure, using Git as the single source of truth. It integrates with Kubernetes, Helm, and other tools to provide a complete GitOps workflow.
- ArgoCD: This is another popular GitOps tool that can deploy and manage applications and infrastructure, using Git as the source of truth. It provides a web-based UI and CLI to manage the GitOps pipeline and integrates with Kubernetes, Helm, and other tools.
- Jenkins X: This is a CI/CD platform that includes GitOps workflows for building, testing, and deploying applications to Kubernetes clusters. It uses GitOps to manage the entire pipeline, from source code to production deployment.
Now that we know what CI/CD is, we can look into various tools that could be used to build such pipelines. In the next section, we will provide you with some examples of a pipeline for cloning the latest version of your repository, building a Docker image, and running some tests.
An example of CI/CD pipelines
Section titled “An example of CI/CD pipelines”Let’s look at a few examples of automation pipelines that will apply our Terraform changes to the different CD tools out there.
Jenkins
Section titled “Jenkins”Jenkins is the most popular open source CI/CD tools out there. It transformed from the clicked-through configuration to the CaaC approach. Its go-to language for defining pipelines is Groovy and Jenkinsfile. The following is an example of Jenkinsfile that will run a plan, ask the user for the input, and run apply if the user approves the change:
pipeline { agent any environment { AWS_ACCESS_KEY_ID = credentials('aws-key-id') AWS_SECRET_ACCESS_KEY = credentials('aws-secret-key') }The preceding code opens a new pipeline definition. It’s defined to run in any available Jenkins agent. Next, we’re setting up environment variables to be used within this pipeline. The environment variables text is being retrieved from the aws-key-id and aws-secret-key Jenkins credentials. These need to be defined before we can run this pipeline.
Next, we’ll define that each step pipeline will run inside the stages block:
stages { stage('Checkout') { steps { checkout scm } }First, we’ll clone our Git repository; the step that does this is checkout scm. The URL will be configured in the Jenkins UI directly:
stage('TF Plan') { steps { dir('terraform') { sh 'terraform init' sh 'terraform plan -out terraform.tfplan' } } }Next, we’ll run terraform init to initialize the Terraform environment. Here, we’re running the plan and saving the output to the terraform.tfplan file, which we will run apply with in the final step:
stage('Approval') { steps { script { def userInput = input(id: 'confirm', message: 'Run apply?', parameters: [ [$class: 'BooleanParameterDefinition', defaultValue: false, description: 'Running apply', name: 'confirm'] ]) } }}This step defines user input. We’ll need to confirm this by running apply after we review the plan’s output. We’re defining the default as false. The pipeline will wait for your input on this step:
stage('TF Apply') { steps { dir('terraform') { sh 'terraform apply -auto-approve -input=false terraform.tfplan' sh 'rm -f terraform.tfplan' } } } }}Finally, if you’ve confirmed that the pipeline will run apply without asking for further user input (-input=false option) and if apply ran without any errors, it will remove the terraform.tfplan file that was created in the plan step.
GitHub Actions basics
Section titled “GitHub Actions basics”It’s possible to create a similar pipeline with GitHub Actions that corresponds to the preceding Jenkinsfile, but unfortunately, GitHub Actions does not support user input while an action is running. We could use the workflow_dispatch option, but it will ask the user for input before the Action runs (see the official documentation for a reference: https://github.blog/changelog/2021-11-10-github-actions-input-types-for-manual-workflows/). So, instead, let’s create an action that will run plan and apply:
name: Terraform Applyon: push: branches: [ main ]The preceding code defines that the GitHub Action will only be triggered on changes to the main branch:
env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}Here, we’re defining environment variables similarly to the Jenkins pipeline. AWS access and secret keys are coming from secrets stored in GitHub that we will need to add beforehand. This won’t be required if our GitHub runner is running inside the AWS environment or we are using GitHub OpenID Connect. You can read about the latter by checking out the GitHub documentation: https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services.
Next, we can define the GitHub Action steps within the jobs block:
jobs: terraform_apply: runs-on: ubuntu-latestHere, we’re defining a job named terraform_apply that will run on the latest version of the Ubuntu runner that’s available in Github Actions:
steps:- name: Checkout code uses: actions/checkout@v2This step checks out the code. We’re using a predefined Action available in GitHub instead of creating a script that will run the Git command line. The exact code it will run is available at https://github.com/actions/checkout:
- name: Setup Terraform uses: hashicorp/setup-terraform@v1The Setup Terraform step will download Terraform for us. By default, it’ll download the latest available version of Terraform, but we can pin an exact version if we need to. The code for the step is available at https://github.com/hashicorp/setup-terraform:
- name: Terraform Plan working-directory: terraform/ run: | terraform init terraform plan -out terraform.tfplanIn the Terraform Plan step, we’re initializing Terraform and running the plan in the same way we did for the Jenkins pipeline:
- name: Terraform Apply working-directory: terraform/ run: | terraform apply -auto-approve –input=false terraform.tfplan rm -f terraform.tfplanFinally, the Terraform Apply step is applying infrastructure changes from the previously saved Terraform plan file, terraform.tfplan, and removing the plan file.
If you want to create a more robust piece of code that will work in every CI/CD tool out there, it’s possible to create a Bash script to do the heavy lifting. With Bash scripting, it’s also much easier to embed some testing before even running the plan. Here’s a sample Bash script that will run the Terraform plan and apply it for you:
#!/usr/bin/env bashset -uset -eHere, we’re setting Bash as a default shell for running this script. In the next few lines, we’re modifying the default settings for the script so that it stops executing when it encounters any unbound variables or errors:
# Check if Terraform binary is in PATHif command -v terraform &> /dev/null; then TERRAFORM_BIN="$(command -v terraform)"else echo "Terraform not installed?" exit 1fiThis code block checks whether Terraform is available in the system and saves the full path to it inside the TERRAFORM_BIN variable, which we will be using later:
# Init terraform backend$TERRAFORM_BIN init -input=falseInitialize the Terraform environment before running the plan:
# Plan changesecho "Running plan..."$TERRAFORM_BIN plan -input=false -out=./terraform.tfplanRun plan and save it to a file for later use:
echo "Running Terraform now"if $TERRAFORM_BIN apply -input=false ./terraform.tfplan; then echo "Terraform finished successfully" RETCODE=0else echo "Failed!" fifiThe preceding code block executes Terraform apply and checks the return code of the command. It also displays appropriate information.
Other major CI/CD solutions use a very similar approach. The biggest difference is between Jenkins, corporate tools, and open source solutions where YAML configuration is the most common. In the next section, we will dig a bit deeper into each stage of the pipeline, focusing on the integration testing for Terraform and deploying changes to the infrastructure.
Continuously integrating and deploying your infrastructure
Section titled “Continuously integrating and deploying your infrastructure”Testing application code is now a de facto standard, especially since the adoption of test-driven development (TDD). TDD is a software development process in which developers write automated tests before writing code.
These tests are designed to fail initially, and developers then write code to make them pass. The code is continuously refactored to ensure it is efficient and maintainable while passing all tests. This approach helps reduce the number of bugs and increase the reliability of the software.
Testing infrastructure is not as easy as that as it’s hard to check whether Amazon Elastic Compute Cloud (EC2) will be successfully started without actually starting the instance. It’s possible to mock API calls to AWS, but it won’t guarantee that the actual API will return the same results as your testing code. With AWS, it would also mean that testing will be slow (we will need to wait for this EC2 instance to come up) and probably generate additional cloud costs.
There are multiple infrastructure testing tools, both integrated with Terraform and third-party software (which is also an open source software).
Integration testing
Section titled “Integration testing”There are multiple basic tests we could run in our CI pipeline. We can detect drift between our actual code and what’s running in the cloud, we can lint our code according to the recommended format, and we can test whether the code is to the letter of our compliance policies. We can also estimate AWS costs from the Terraform code. Harder and more time-consuming processes include unit testing and end-to-end testing of our code. Let’s take a look at the available tools we could use in our pipeline.
Most basic tests we could be running from the start involve simply running terraform validate and terraform fmt. The former will check whether the syntax of the Terraform code is valid (meaning there are no typos in resources and/or variables, all required variables are present, and so on). The fmt check will update the formatting of the code according to the Terraform standards, which means that all excessive white spaces will be removed, or some white spaces may be added to align the = sign for readability. This may be sufficient for simpler infrastructure and we recommend adding those tests from the start as it’s pretty straightforward to do. You can reuse parts of the code we provided earlier to bootstrap the process for your existing code.
Infrastructure costs
Section titled “Infrastructure costs”Infrastructure costs are not a functional, static, or unit test you could be running in your testing pipeline. Although it’s very useful to monitor that aspect of your infrastructure, your manager will also be happy to know when the AWS budget is checking out with predictions.
Infracost.io is a cloud cost estimation tool that allows you to monitor and manage infrastructure costs by providing real-time cost analysis for cloud resources. With Infracost.io, you can estimate the cost of infrastructure changes and avoid any unexpected costs by providing cost feedback at every stage of the development cycle.
Integrating Infracost.io into GitHub Actions is a straightforward process that involves creating an Infracost.io account and generating an API key that will allow you to access the cost estimation data.
Next, you need to install the Infracost.io CLI on your local machine. The CLI is a command-line tool that allows you to calculate and compare infrastructure costs.
After installing the CLI, you can add an Infracost.io action to your GitHub workflow by creating a new action file – for example, .github/workflows/infracost.yml.
In the Infracost.io action file, you need to specify the Infracost.io API key and the path to your Terraform configuration files:
name: Infracoston: push: branches: - mainjobs: infracost: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Run Infracost uses: infracost/infracost-action@v1 with: api_key: ${{ secrets.INFRACOST_API_KEY }} terraform_dir: ./terraformFinally, commit and push the changes to your GitHub repository. Whenever a new Terraform configuration file is pushed to the repository, the Infracost.io action will automatically calculate the cost estimation and provide feedback on the GitHub Actions page.
Infracost is free for open source projects, but it’s also possible to create your own service for monitoring cloud costs. A GitHub repository for Infracost can be found at https://github.com/infracost/infracost.
By integrating it into your CI pipeline, you can proactively monitor and manage your infrastructure costs and make informed decisions on infrastructure changes before deploying it to your cloud account.
Drift testing
Section titled “Drift testing”One of the challenges of managing infrastructure with Terraform is ensuring that the actual state of the infrastructure matches the desired state defined in the Terraform configuration files. This is where the concept of drift comes in.
Drift occurs when there is a difference between the desired state of the infrastructure and its actual state. For example, if a resource that was created using Terraform is manually modified outside of Terraform, the actual state of the infrastructure will differ from the desired state defined in Terraform configuration files. This can cause inconsistencies in the infrastructure and may lead to operational issues.
To detect drift in the infrastructure, Terraform provides a command called terraform plan. When this command is run, Terraform compares the desired state defined in the Terraform configuration files with the actual state of the infrastructure and generates a plan of the changes that need to be made to bring the infrastructure back into the desired state. If there are any differences between the desired and actual states, Terraform will show them in the plan output.
It’s also possible to use third-party tools that will extend this feature of Terraform. One of these tools is Driftctl.
Driftctl is an open source tool that helps detect drift in cloud infrastructure managed by Terraform. It scans the actual state of the infrastructure resources and compares them against the desired state defined in Terraform configuration files to identify any discrepancies or differences. Driftctl supports a wide range of cloud providers, including AWS, Google Cloud, Microsoft Azure, and Kubernetes.
Driftctl can be used in various ways to detect drift in infrastructure. It can be integrated with a CI/CD pipeline to automatically detect drift and trigger corrective actions. It can also be run manually to check for drift on demand.
Here’s an example GitHub pipeline that utilizes Driftctl to detect infrastructure drift:
name: Detect Infrastructure Drifton: push: branches: - mainThe preceding code indicates that this pipeline will run only on the main branch.
Here, we’re defining a job called detect-drift that will run on the latest Ubuntu Linux runner available:
jobs: detect-drift: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2Next, we’re starting to define what we’re going to do in each step of the pipeline – first, we will use a predefined action that will run git clone on the runner:
- name: Install Terraform run: | sudo apt-get update sudo apt-get install -y unzip curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add - sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main" sudo apt-get update && sudo apt-get install terraformThe next step we’re defining is a shell script that will install, unzip, and download Terraform from the public repository published by HashiCorp:
- name: Install Driftctl run: | curl https://github.com/cloudskiff/driftctl/releases/download/v0.8.2/driftctl_0.8.2_linux_amd64.tar.gz -sSLo driftctl.tar.gz tar -xzf driftctl.tar.gz sudo mv driftctl /usr/local/bin/In this step, we will install the Driftctl tool by downloading an archive from the public release on GitHub. We will extract it and move the binary to the / usr/local/bin directory:
- name: Initialize Terraform run: terraform init- name: Check Terraform Configuration run: terraform validateThe preceding steps simply involve running terraform init and terraform validate to verify whether we can access the Terraform backend and whether the code we intend to check in the next few steps is valid from a syntax perspective:
- name: Detect Drift with Driftctl run: | driftctl scan –from tfstate://./terraform.tfstate –output json > drift.json- name: Upload Drift Report to GitHub uses: actions/upload-artifact@v2 with: name: drift-report path: drift.jsonThe final two steps are running the Driftctl tool and saving their findings inside the driftctl.json file, which is uploaded to GitHub artifacts with the name drift-report.
To summarize, this pipeline runs on the main branch and performs the following steps:
- Checks out the code from the GitHub repository.
- Installs
terraformanddriftctl. - Initializes Terraform and validates the Terraform configuration files.
- Uses
driftctlto scan the actual state of the infrastructure resources and compares them against the desired state defined in the Terraform configuration files to detect any drift. The output of this scan is saved to a JSON file calleddrift.json. - Uploads the
drift.jsonfile as an artifact to GitHub, making it available for further analysis.
Additionally, this pipeline can be customized to meet specific requirements, such as integrating with a CI/CD pipeline or running on a schedule to regularly check for drift in the infrastructure.
The need for installing driftctl and terraform on every pipeline run is not desired, so we recommend that you prepare your own Docker image with preinstalled proper versions of those tools and use that instead. It will also increase your security along the way.
You can find more information about the project on the website: https://driftctl.com/.
Security testing
Section titled “Security testing”Testing infrastructure security is an essential aspect of maintaining secure and stable systems. As modern infrastructure is often defined and managed as code, it is necessary to test it just like any other code. Infrastructure as Code (IaC) testing helps identify security vulnerabilities, configuration issues, and other flaws that may lead to system compromise.
There are several automated tools available that can aid in infrastructure security testing. These tools can help identify potential security issues, such as misconfigured security groups, unused security rules, and unsecured sensitive data.
There are several tools we can use to test security as a separate process from the CI pipeline:
- Prowler: This is an open source tool that scans AWS infrastructure for security vulnerabilities. It can check for issues such as AWS Identity and Access Management (IAM) misconfigurations, open security groups, and S3 bucket permission issues.
- CloudFormation Guard: This is a tool that validates AWS CloudFormation templates against a set of predefined security rules. It can help identify issues such as open security groups, unused IAM policies, and non-encrypted S3 buckets.
- OpenSCAP: This is a tool that provides automated security compliance testing for Linux-based infrastructure. It can scan the system for compliance with various security standards, such as the Payment Card Industry Data Security Standard (PCI DSS) or National Institute of Standards and Technology Special Publication 800-53 (NIST SP 800-53).
- InSpec: This is another open source testing framework that can be used for testing infrastructure compliance and security. It has built-in support for various platforms and can be used to test against different security standards, such as the Health Insurance Portability and Accountability Act (HIPAA) and Center for Internet Security (CIS).
Here, we’re focusing on integrating some security testing within the CI. The tools we could integrate here are as follows:
- tfsec is an open source static analysis tool for Terraform code. It scans Terraform configurations to detect potential security issues and provides suggestions for remediation. It has built-in support for various cloud providers and can help identify issues such as weak authentication, insecure network configurations, and unencrypted data storage. Its GitHub repository can be found at https://github.com/aquasecurity/tfsec.
- Terrascan is an open source tool for static code analysis of IaC files. It supports various IaC file formats, including Terraform, Kubernetes YAML, and Helm charts, and scans them for security vulnerabilities, compliance violations, and other issues. Terrascan can be integrated into a CI/CD pipeline and helps ensure that infrastructure deployments are secure and compliant with industry standards. Its GitHub repository can be found at https://github.com/tenable/terrascan.
- CloudQuery is an open source tool that enables users to test security policies and compliance across different cloud platforms, including AWS, Google Cloud Platform (GCP), and Microsoft Azure. It provides a unified query language and interface to access cloud resources, allowing users to analyze configurations and detect potential security vulnerabilities. CloudQuery integrates with various CI/CD pipelines, making it easy to automate testing for security policies and compliance. Users can also customize queries and rules based on their specific needs and standards. You can read more about this topic in their blog post: https://www.cloudquery.io/how-to-guides/open-source-cspm.
Let’s look at the example GitHub pipeline that’s integrating the terrascan tool:
name: Terrascan Scanon: [push]jobs: scan: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Install Terrascan run: | wget https://github.com/accurics/terrascan/releases/latest/download/terrascan_linux_amd64.zip unzip terrascan_linux_amd64.zip rm -f terrascan_linux_amd64.zip sudo mv terrascan /usr/local/bin/ - name: Run Terrascan run: | terrascan scan -f ./path/to/infrastructure/codeIn this workflow, the on: [push] line specifies that the workflow should be triggered whenever changes are pushed to the repository.
The jobs section contains a single job called scan. The runs-on key specifies that the job should run on an Ubuntu machine.
The steps section contains three steps:
- It checks out the code from the repository using the
actions/checkoutaction. - It downloads and installs Terrascan on the machine using the
wgetandunzipcommands. Note that this step assumes that you’re running the workflow on a Linux machine. - It runs Terrascan to scan the infrastructure code. You’ll need to replace
./path/to/infrastructure/codewith the actual path to your infrastructure code.
Once you’ve created this workflow and pushed it to your GitHub repository, GitHub Actions will automatically run the workflow whenever changes are pushed to the repository. You can view the results of the Terrascan scan in the workflow logs.
Let’s move on to infrastructure unit testing. There are generally two options at the moment: Terratest when testing HCL code directly or CDKTF / Pulumi if you want to use more advanced programming languages to maintain your IaC.
Testing with Terratest
Section titled “Testing with Terratest”Terratest is an open source testing framework for infrastructure code, including HCL code for Terraform. It was first released in 2017 by Gruntwork, a company that specializes in infrastructure automation and offers a set of pre-built infrastructure modules called the Gruntwork IaC Library.
Terratest is designed to simplify testing infrastructure code by providing a suite of helper functions and libraries that allow users to write automated tests written in Go, a popular programming language for infrastructure automation. Terratest can be used to test not only Terraform code but also infrastructure built with other tools such as Ansible, Packer, and Docker.
One of the key benefits of Terratest is that it allows developers to test their infrastructure code in a production-like environment, without the need for a dedicated test environment. This can be achieved by using tools such as Docker and Terraform to spin up temporary infrastructure resources for testing purposes.
Terratest also provides a range of test types, including unit tests, integration tests, and end-to-end tests, allowing users to test their infrastructure code at different levels of abstraction. This helps ensure that code changes are thoroughly tested before they are deployed to production, reducing the risk of downtime or other issues.
An example of testing an aws_instance resource we created in a module in the previous chapter would look like this:
package testimport ( "testing" "github.com/gruntwork-io/terratest/modules/aws" "github.com/gruntwork-io/terratest/modules/terraform" "github.com/stretchr/testify/assert")func TestAwsInstance(t *testing.T) { terraformOptions := &terraform.Options{ TerraformDir: "../path/to/terraform/module", } defer terraform.Destroy(t, terraformOptions) terraform.InitAndApply(t, terraformOptions) instanceID := terraform.Output(t, terraformOptions, "aws_instance_id") instance := aws.GetEc2Instance(t, "us-west-2", instanceID) assert.Equal(t, "t3.micro", instance.InstanceType) assert.Equal(t, "TestInstance", instance.Tags["Name"])}In this example, we first define a test function called TestAwsInstance using the standard Go testing library. Inside the function, we create a terraformOptions object that specifies the directory of our Terraform module.
Then, we use the terraform.InitAndApply function to initialize and apply the Terraform configuration, creating the AWS EC2 instance resource.
Next, we use the aws.GetEc2Instance function from the Terratest AWS module to retrieve information about the instance that was created, using its ID as input.
Finally, we use the assert library from the testify package to write assertions that validate the properties of the instance, such as its instance type and tags. If any of the assertions fail, the test will fail.
To run this example, you will need to ensure that you have installed the Terratest and AWS Go modules, and have valid AWS credentials set up in your environment.
Unit testing with CDKTF
Section titled “Unit testing with CDKTF”AWS Cloud Development Kit for Terraform (CDKTF) is an open source framework for Terraform that allows developers to define the infrastructure and services inside any cloud solution Terraform supports using programming languages such as TypeScript, Python, and C#. It enables the creation of IaC using high-level object-oriented abstractions, reducing the complexity of writing and maintaining infrastructure code.
CDKTF was initially released in March 2020, and it is a collaboration between AWS and HashiCorp, the company behind Terraform. CDKTF leverages the best of both worlds: the familiarity and expressiveness of modern programming languages, and the declarative, multi-cloud capabilities of Terraform.
TypeScript is the most popular language used with CDKTF, and it provides a type-safe development experience with features such as static type-checking, code completion, and refactoring.
As an example, let’s reuse the Terraform code from Chapter 12:
resource "aws_instance" "vm_example" { ami = "ami-830c94e3" instance_type = "t2.micro" tags = { Name = "DevOpsGuideTerraformExample"}The equivalent code in CDKTF in Python would look like this:
#!/usr/bin/env pythonfrom constructs import Constructfrom cdktf import App, TerraformStackfrom cdktf_cdktf_provider_aws.provider import AwsProviderfrom cdktf_cdktf_provider_aws.instance import Instancefrom cdktf_cdktf_provider_aws.data_aws_ami import DataAwsAmi, DataAwsAmiFilterHere, we’re importing all required modules. The first line of the script says that the default interpreter for it should be a Python interpreter that’s available in the system:
class MyStack(TerraformStack): def __init__(self, scope: Construct, id: str): super().__init__(scope, id) AwsProvider(self, "AWS", region="eu-central-1")In the preceding line, we’re configuring a default provider to use the eu-central-1 region. Let’s see what’s next:
ec2_instance = Instance( self, id_="ec2instanceName", instance_type="t2.micro" ami="ami-830c94e3", )app = App()MyStack(app, "ec2instance")app.synth()The following is an example unit test for the preceding code that uses the unittest Python module and the usual syntax for TDD in Python:
import unittestfrom your_cdk_module import MyStack # Replace 'your_cdk_module' with the actual module name containing the MyStack classclass TestMyStack(unittest.TestCase): def test_ec2_instance(self): app = App() stack = MyStack(app, "test-stack") # Get the EC2 instance resource created in the stack ec2_instance = stack.node.try_find_child("ec2instance") # Assert EC2 instance properties self.assertEqual(ec2_instance.ami, "ubuntuAMI") self.assertEqual(ec2_instance.instance_type, "t3.micro") self.assertEqual(ec2_instance.key_name, "admin_key") self.assertEqual(ec2_instance.subnet_id, "subnet-1234567890")if __name__ == '__main__': unittest.main()As stated previously, unfortunately, the instance must be running in AWS for us to test whether we have the desired tags and other properties available through the CDKTF. The instance is being created by the setUp() function and terminated with the tearDown() function. Here, we’re using a small instance that is Free Tier eligible, but with bigger instances, it will generate some costs.
Experimental Terraform testing module
Section titled “Experimental Terraform testing module”The final but very interesting option is using the testing Terraform module. This module allows you to write Terraform (HCL) code tests, also in the same language. This will potentially make it much easier to write tests as the current options we’ve already gone through cover writing tests in Golang or by using CTKTF.
At the time of writing, the module is considered highly experimental, but it’s worth keeping an eye on how it will develop in the future.
The module’s website can be found at https://developer.hashicorp.com/terraform/language/modules/testing-experiment.
Other integration tools worth mentioning
Section titled “Other integration tools worth mentioning”There is a galaxy of other testing tools out there, and more are being developed as you read this. The following is a short list of tools worth mentioning that we didn’t have enough space to describe properly:
- Checkov (https://www.checkov.io/): This is an open source IaC static analysis tool that helps developers and DevOps teams identify and fix security and compliance issues early in the development life cycle.
- Super-linter (https://github.com/github/super-linter): This is an open source code linting tool that can automatically detect and flag issues in various programming languages and help maintain consistent code quality.
- Trivy (https://github.com/aquasecurity/trivy): This is a vulnerability scanner for container images that helps developers and DevOps teams identify and fix vulnerabilities in their containerized applications.
- Kitchen-Terraform (https://github.com/newcontext-oss/kitchen-terraform): This tool is part of the Test Kitchen plugin collection and allows systems to utilize Test Kitchen to apply and validate Terraform configurations with InSpec controls.
- RSpec-Terraform (https://github.com/bsnape/rspec-terraform): This tool provides RSpec tests for Terraform modules. RSpec is a behavior-driven development (BDD) testing framework for Ruby that allows developers to write expressive and readable tests in a domain-specific language (DSL).
- Terraform-Compliance (https://github.com/terraform-compliance/cli): This is a BDD testing tool designed for Terraform files.
- Clarity (https://github.com/xchapter7x/clarity): This is a declarative Terraform test framework that specializes in unit testing.
In conclusion, we have a lot of testing options available. This could be overwhelming for some. Testing the Terraform code is still in development, similar to the other IaC solutions we’ve mentioned. When implementing CI pipelines, it’s best to focus on the low-hanging fruits at the beginning (format checking, running terraform plan, and so on) and add more testing during development. We realize it’s a hard thing to accomplish, but we believe that investing in this will enable us to make infrastructure changes with more confidence and protect us from unintentional outages.
In the next section, we will focus on various CD solutions, both SaaS and self-hosted.
Deployment
Section titled “Deployment”Continuous deployment in terms of Terraform comes down to running terraform apply. This can be done automatically with a simple Bash script, but the hard part is to integrate this into the CD tool to ensure we won’t remove any data by mistake with confidence. Assuming we have done a great job with our integration testing and we’re confident enough to do it without any further user interaction, we can enable it to run automatically.
Previously, we’ve shown examples of using Jenkins, GitHub Actions, and even a Bash script that we could embed into the process to automate it. We can successfully use these solutions to deploy our changes to the infrastructure; however, there are already dedicated solutions for that. Let’s take a look at the most popular ones, starting with SaaS offerings from the company behind Terraform – HashiCorp.
HashiCorp Cloud and Terraform Cloud
Section titled “HashiCorp Cloud and Terraform Cloud”HashiCorp is a software company that provides various tools for infrastructure automation and management. Two of the most popular products offered by HashiCorp are HashiCorp Cloud and Terraform Cloud.
HashiCorp Cloud is a cloud-based service that provides a suite of tools for infrastructure automation and management. It includes HashiCorp’s popular tools such as Terraform, Vault, Consul, and Nomad. With HashiCorp Cloud, users can create and manage their infrastructure using the same tools that they use locally.
On the other hand, Terraform Cloud is a specific offering from HashiCorp that focuses solely on the IaC tool Terraform. Terraform Cloud provides a central place for teams to collaborate on infrastructure code, store configuration state, and automate infrastructure workflows. It offers several features, such as workspace management, version control, and collaboration tools, that make it easier for teams to work together on large-scale infrastructure projects.
One of the key differences between HashiCorp Cloud and Terraform Cloud is that the former offers a suite of tools for infrastructure automation and management, while the latter is specifically focused on Terraform.
Scalr is a cloud management platform that provides enterprise-level solutions for cloud infrastructure automation and management. It was founded in 2007 by Sebastian Stadil to simplify the process of managing multiple cloud environments.
Scalr is a multi-cloud management platform. It comes in two flavors: commercial, which is hosted by the parent company as a SaaS solution, and open source, which you can deploy yourself. It can run your Terraform code, but it has more features, such as cost analysis, which will present the estimated bill from the cloud provider for the infrastructure you are deploying. It comes with a web UI, abstracting a lot of work that needs to be done when working with IaC. As we mentioned previously, it is a multi-cloud solution and it comes with a centralized single sign-on (SSO) that lets you view and manage all your cloud environments from one place. It comes with roles, a modules registry, and so on. It is a good solution if you are looking for more than just a centralized IaC tool.
Spacelift
Section titled “Spacelift”Spacelift is a cloud-native IaC platform that helps development teams automate and manage their infrastructure with Terraform, Pulimi, or CloudFormation. It also supports automation of Kubernetes using kubectl and Ansible CaaC.
The platform offers a range of features, such as version control, automated testing, and continuous delivery, allowing teams to accelerate their infrastructure deployment cycles and reduce the risk of errors. Spacelift also provides real-time monitoring and alerts, making it easy to identify and resolve issues before they cause downtime or affect user experience.
Spacelift was founded in 2020 by a team of experienced DevOps and infrastructure engineers who recognized the need for a better way to manage IaC. The company has since grown rapidly, attracting customers from a wide range of industries, including healthcare, finance, and e-commerce.
The official website can be found at https://spacelift.com.
Env0 is a SaaS platform that enables teams to automate their infrastructure and application delivery workflows with Terraform. It was founded in 2018 by a team of experienced DevOps engineers who recognized the need for a streamlined and easy-to-use solution for managing IaC.
Env0 offers a variety of features and integrations to help teams manage their Terraform environments, including automated environment provisioning, integration with popular CI/CD tools such as Jenkins and CircleCI, and support for multiple cloud providers, including AWS, Azure, and Google Cloud.
As a private company, Env0 does not publicly disclose its financial information. However, they have received significant funding from venture capital firms, including a $3.5 million seed round in 2020 led by Boldstart Ventures and Grove Ventures.
Env0 has quickly established itself as a leading SaaS provider for managing Terraform environments and streamlining DevOps workflows and looks like a very interesting option to us in your environment.
The official website can be found at https://www.env0.com/.
Atlantis
Section titled “Atlantis”Atlantis is an open source project that aims to simplify the management of Terraform infrastructure code by providing a streamlined workflow for creating, reviewing, and merging pull requests. The first release of Atlantis was made in 2018 and it has since gained popularity among developers and DevOps teams who use Terraform as their IaC tool.
Atlantis works by integrating with your existing version control system, such as GitHub or GitLab, and continuously monitors for pull requests that contain Terraform code changes. When a new pull request is opened, Atlantis automatically creates a new environment for the changes and posts a comment in the pull request with a link to the environment. This allows reviewers to quickly and easily see the changes in a live environment and provide feedback. Once the changes have been reviewed and approved, Atlantis can automatically merge the pull request and apply the changes to the target infrastructure.
This open source tool is the one we will dive deeper into. Since its source code is available for free, you will be able to download it yourself and deploy it on your local environment or inside the public cloud. Let’s deploy Atlantis in AWS and configure a simple infrastructure to be managed by it.
CI/CD with Atlantis
Section titled “CI/CD with Atlantis”Armed with the knowledge about tooling and principles around CI/CD (both delivery and deployment), we will create a CI/CD pipeline with the use of Git and the open source tool Atlantis. We will automatically test and deploy changes to our AWS infrastructure with it and do basic testing along the way.
Deploying Atlantis to AWS
Section titled “Deploying Atlantis to AWS”We will use the Terraform module created by Anton Bobenko from the terraform-aws-modules project on GitHub. Here is the Terraform Registry link to the module: https://registry.terraform.io/modules/terraform-aws-modules/atlantis/aws/latest.
You can use this module in two ways. First, which is natural, is using it in your existing Terraform code to deploy it in AWS. The second, which we will use for this demonstration, is using the module as a standalone project. The module will also create a new Virtual Private Cloud (VPC) for you in the eu-west AWS zone and Atlantis will be running inside the AWS ECS service. This will generate some infrastructure costs.
To do so, we need to clone the GitHub repository:
git clone [email protected]:terraform-aws-modules/terraform-aws-atlantis.gitCloning into 'terraform-aws-atlantis'...Host key fingerprint is SHA256:+Aze234876JhhddEremote: Enumerating objects: 1401, done.remote: Counting objects: 100% (110/110), done.remote: Compressing objects: 100% (101/101), done.remote: Total 1400 (delta 71), reused 81 (delta 52), pack-reused 1282Receiving objects: 100% (1401/1401), 433.19 KiB | 1.12 MiB/s, done.Resolving deltas: 100% (899/899), done.Next, we will have to create a Terraform variables file. We have some boilerplate in the repository in the terraform.tfvars.sample file. Let’s copy it:
cp terraform.tfvars.sample terraform.tfvarsBefore proceeding, make sure you’ve created a GitHub repository that will hold all your Terraform code. We will be creating a Webhook for this repository when Atlantis is deployed, but you will need to add it to the terraform.tfvars file before applying it.
Let’s take a look at the variables in the terraform.tfvars file we will be able to change:
cidr = "10.10.0.0/16"azs = ["eu-west-1a", "eu-west-1b"]private_subnets = ["10.10.1.0/24", "10.10.2.0/24"]public_subnets = ["10.10.11.0/24", "10.10.12.0/24"]route53_zone_name = "example.com"ecs_service_assign_public_ip = trueatlantis_repo_allowlist = ["github.com/terraform-aws-modules/*"]atlantis_github_user = ""atlantis_github_user_token = ""tags = { Name = "atlantis"}atlantis_repo_allowlist is the first one you would need to update to match the repositories you’d like Atlantis to be able to use. Make sure it’s pointing to your repository. route53_zone_name should be changed as well to something similar, such as automation.yourorganisation.tld. Note that it needs to be a public domain – GitHub will use it to send webhooks over to Atlantis to trigger builds. You will need to create the Route53 hosted DNS zone in your Terraform code or use the web console.
Two more variables you will need to update are atlantis_github_user and atlantis_github_user_token. The first one is self-explanatory, but for the second, you will need to visit the GitHub website and generate your personal access token (PAT). This will allow Atlantis to access the repository you want to use. To do that, you will need to follow the guidelines on the GitHub documentation pages: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token.
After updating the terraform.tfvars file, we’re ready to run terraform init and terraform plan:
admin@myhome~/aws$ terraform initInitializing modules...# output truncated for readability- Installed hashicorp/random v3.4.3 (signed by HashiCorp)Terraform has been successfully initialized!Terraform has created a lock file called .terraform.lock.hcl to record the provider selections it made. Include this file in your version control repository so that Terraform will make the same selections by default when you run terraform init in the future.
Now, we can run the following terraform plan command:
admin@myhome~/aws$ terraform planTerraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create <= read (data resources)Terraform will perform the following actions:# Output truncated for readability # aws_cloudwatch_log_group.atlantis will be created + resource "aws_cloudwatch_log_group" "atlantis" { + arn = (known after apply) + id = (known after apply) + name = "atlantis" + name_prefix = (known after apply) + retention_in_days = 7 + skip_destroy = false + tags = { + "Name" = "atlantis" } + tags_all = { + "Name" = "atlantis" } }# Removed some output for readabilityPlan: 49 to add, 0 to change, 0 to destroy.If you see a similar output, you can apply it. The module will also return a lot of information about the created resources. It’s worth paying attention to them.
After running terraform apply (it will take a couple of minutes), you will see an output similar to the following:
Apply complete! Resources: 49 added, 0 changed, 0 destroyed.Outputs:alb_arn = "arn:aws:elasticloadbalancing:eu-central-1:673522028003:loadbalancer/app/atlantis/8e6a5c314c2936bb"# Output truncated for readabilityatlantis_url = "https://atlantis.atlantis.devopsfury.com"atlantis_url_events = "https://atlantis.atlantis.devopsfury.com/events"public_subnet_ids = [ "subnet-08a96bf6a15a65a20", "subnet-0bb98459f42567bdb",]webhook_secret = <sensitive>If you’ve done everything correctly, you should be able to access the Atlantis website under the atlantis.automation.yourorganisation.tld domain we created previously. The module added all the necessary records to the Route53 zone for us.
If everything has gone well up to this point, when you visit https://atlantis.automation.yourorganisation.tld, you will see the following Atlantis panel:

Figure 13.1 – Atlantis website after successfully deploying it using the Terraform module
The webhook_secret output that’s marked as sensitive in the preceding output will be used to set up a webhook on the GitHub repository side. To view it, you will need to run the following command:
admin@myhome:~/aws$ terraform output webhook_secret"bf3b20b285c91c741eeff34621215ce241cb62594298a4cec44a19ac3c70ad3333cc97d9e8b24c06909003e5a879683e4d07d29efa750c47cdbeef3779b3eaef"We can also automate it with Terraform by using the module available in the same repository as the Atlantis one.
Here’s the full URL to the module: https://github.com/terraform-aws-modules/terraform-aws-atlantis/tree/master/examples/github-repository-webhook.
Alternatively, you can create a webhook manually for testing by going to the GitHub website and following the documentation: https://docs.github.com/en/webhooks-and-events/webhooks/creating-webhooks.
Remember to use the secret generated automatically by Terraform in the output variable – that is, webhook_secret.
Creating webhook documentation is also well described in the Atlantis documentation: https://www.runatlantis.io/docs/configuring-webhooks.html#github-github-enterprise.
You may encounter that Atlantis won’t come up as expected and you will see an HTTP 500 error issue when accessing the web panel. To track down any issues with this service, such as Atlantis is still unavailable or responding with errors to the GitHub webhook, you can go to the AWS console and find the ECS service. From there, you should see a cluster named atlantis. If you click on it, you’ll see the configuration and status of the cluster, as shown in the following figure:

Figure 13.2 – Amazon Elastic Container Service (ECS) Atlantis cluster information
If you go to the Tasks tab (visible in the preceding screenshot) and click on the task ID (for example, 8ecf5f9ced3246e5b2bf16d7485e981c), you will see the following information:

Figure 13.3 – Details of the task inside the Atlantis ECS cluster
The Logs tab will show you all recent events.
You can view more detailed log information in the CloudWatch service when you go to the Logs | Log groups section and find the atlantis log group. Inside, you will be able to see log streams containing all the logs from your task. If you already have multiple streams, it’s possible to quickly track down the correct stream by its Task ID:

Figure 13.4 – CloudWatch log streams containing logs from ECS tasks running Atlantis
If everything has worked fine so far, we’re ready to test whether Atlantis can run terraform plan and terraform apply. Let’s get back to our code.
Running Terraform using Atlantis
Section titled “Running Terraform using Atlantis”To execute terraform plan, we will have to create a new pull request on our GitHub repository. Let’s create a module that will create an S3 bucket and DynamoDB table for us. The main.tf file will look like this:
# Configure the AWS Providerprovider "aws" { region = var.region}The preceding code configures the AWS provider to use the region specified inside the region variable.
This Terraform code block configures a required Terraform version and where the Terraform state file is located. In this example, we’re using local storage, but in a production environment, we should use a remote state location.
terraform { required_version = ">=1.0" backend "local" { path = "tfstate/terraform.local-tfstate" }}resource "aws_s3_bucket" "terraform_state" { bucket = "terraform-states" acl = "private" force_destroy = false versioning { enabled = true }The preceding block defines an S3 bucket where we intend to store a Terraform state. It is a private S3 bucket with enabled versioning. This is the recommended setup for storing state files.
server_side_encryption_configuration { rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } } }}The preceding code also configures server-side encryption (SSE) for the S3 bucket.
resource "aws_dynamodb_table" "dynamodb-terraform-state-lock" { name = "terraform-state-lock" hash_key = "LockID" read_capacity = 1 write_capacity = 1 attribute { name = "LockID" type = "S" } tags = { Name = "DynamoDB Terraform State Lock Table" }}The preceding code block defines a DynamoDB table that’s used for Terraform state locking. The variables.tf file will only contain one variable:
variable "region" { type = string default = "eu-central-1"}After adding these files to Git and committing the changes and creating a new pull request on GitHub, you will be able to ask Atlantis to run a plan and apply for you. If you run a plan, Atlantis will lock the module you’ve modified and no one else will be able to apply any changes to it unless you unlock or apply your changes.
To trigger a plan for your new pull request, just add a comment to your pull request stating atlantis plan. After a while, depending on how big the module is, you will get a plan output similar to what’s shown in the following screenshot:

Figure 13.5 – Interaction with Atlantis on GitHub
At the time of writing, Atlantis doesn’t support automatically applying the changes. However, it’s possible to automate at the CI level. For example, when using GitHub, you could create a GitHub Action that would, after a successful test, add the atlantis apply comment, which would trigger Atlantis to apply changes and report back with the status.
At this point, we can give developers the power to modify our infrastructure without directly allowing them to run Terraform on their local machines. At the same time, we’re removing the possibility of applying changes by many users at the same time, which, without a distributed locking mechanism, can be very destructive. Furthermore, working with Terraform will be easier as no one will have to install it on local machines, no one will have to have direct access to our AWS account, and we will gain more visibility of changes to our infrastructure.
Building CI/CD with Terraform still has a long way to go. IaC is still behind testing features available in other programming languages, but many developers are working on it. We’re looking forward to making testing infrastructure easier for everybody.
Summary
Section titled “Summary”In this chapter, we explored the benefits of using Terraform for IaC and discussed the importance of incorporating CI/CD processes in Terraform workflows. We covered testing infrastructure and various tools for automating deployment.
In the final section, we explained how to deploy Atlantis, an open source tool for automated Terraform pull request previews, to AWS and configure GitHub to trigger terraform plan and terraform apply. With Atlantis, Terraform users can collaborate on infrastructure changes through GitHub pull requests, allowing for infrastructure changes to be reviewed and approved before they are applied to production. By incorporating Atlantis into your Terraform workflow, you can improve collaboration, reduce errors, and achieve faster and more secure infrastructure changes.
In the final chapter, we will slow down a little and talk about DevOps misconceptions and antipatterns, and how to avoid them.
Exercises
Section titled “Exercises”Try out the following exercises to test your knowledge of this chapter:
- Try to deploy Atlantis locally by following the documentation found at https://www.runatlantis.io/guide/testing-locally.html.
- Create a repository and configure the webhook and PAT for yourself. Run a plan for your new repository (hint: instead of AWS resources, you can use a null resource for testing).
- Create an account on one of the CD solution websites and try to run a plan using this SaaS. There’s usually a free plan for public repositories.