Sling Academy
Home/DevOps/Using Terraform and GitHub Actions for CI/CD pipelines

Using Terraform and GitHub Actions for CI/CD pipelines

Last updated: February 03, 2024

Overview

Continuous Integration and Continuous Deployment (CI/CD) pipelines are crucial for the development cycle, allowing teams to automate testing and deployment. This tutorial outlines how to utilize Terraform with GitHub Actions to create an efficient, automated CI/CD pipeline. Whether you’re new to these tools or have some experience, this guide aims to offer insights at various levels.

Prerequisites:

  • A GitHub account and a basic understanding of how GitHub works.
  • Basic knowledge of Infrastructure as Code (IaC) concepts and Terraform.
  • An AWS (Amazon Web Services) account for hosting resources deployed by Terraform.

Phase 1: Setting Up Your Terraform Project

First, you need a Terraform project. Here’s a simple setup:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 2.68"
    }
  }
}

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Initialize your project with terraform init and then apply it with terraform apply to create an AWS instance. This is your base for the CI/CD pipeline.

Phase 2: Setting Up GitHub Actions

Create a .github/workflows directory in your project with a YAML file for your CI pipeline, for example, terraform_ci.yml:

name: Terraform CI

on:
  push:
    branches:
      - main

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v1
        with:
          terraform_version: 0.12.29
      - name: Terraform Init
        run: terraform init
      - name: Terraform Validate
        run: terraform validate
      - name: Terraform Plan
        run: terraform plan

This script triggers on a push to the main branch, checks out the code, sets up Terraform, and runs terraform init and terraform plan.

Phase 3: Implementing CI/CD with Terraform and GitHub Actions

Extend the terraform_ci.yml file to include deployment:

      - name: Terraform Apply
        run: terraform apply -auto-approve
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

Use GitHub Secrets to securely store your AWS credentials. Navigate to your repository settings, find the Secrets section, and add AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY there.

Now, every push to the main branch not only triggers validation but also automatically deploys your infrastructure changes.

Advanced Usage

For more complex scenarios, such as when working with different environments (dev, staging, production), you can expand your workflow with conditional steps or use different workflow files for each environment. An example would be to include a stepping process that requires a manual approval before deploying to production. This can be done by adding a workflow_dispatch or environment condition to trigger the action manually or upon certain conditions.

Conclusion

By combining Terraform with GitHub Actions, you establish a powerful CI/CD pipeline that automates testing and deployment across various environments. This guide provided a foundation, but as you evolve in your CI/CD journey, consider exploring further customizations and optimizations to fit your project’s specific needs.

Next Article: Terraform: Working with the terraform_login command

Previous Article: Using Rover to visualize Terraform resource dependencies

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide