Guide to Create Github Actions Workflow for Terraform and AWS
Published: 2022-10-29 17:52:29


## Terraform and AWS GitHub Action Workflow

## Table of Contents
- [Introduction](#introduction)
- [GitHub Actions Brief Intro](#github-actions-brief-intro)
- [Intro to Workflow Yaml Blocks](#intro-to-workflow-yaml-blocks)
- [Workflow Yaml for Terraform AWS Pipeline](#workflow-yaml-for-terraform-aws-pipeline)
- [Demo Video](#demo-video)
- [Conclusion](#conclusion)
- [References](#references)

## Introduction
Infra as code using Terraform on AWS Cloud provider is most common use case. So as part of this blog, we will discuss how to create Github Actions workflow for Terraform AWS resource code validation checks.

This workflow (or pipeline) can be configured for testing the terraform code pushed by DevOps engineers/SREs/Developers, and can be triggered whenever there is new tf code is pushed into a specific branch for AWS resource creation

Please refer the screenshot below, this is how the workflow can be triggered from GitHub Actions:

![TF workflow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/93s76beu1etc5mfjh2lw.png)

There are multiple ways to create the automation flow for AWS and Terraform resource creation. You can consider this guide as one of the many ways that are available.

## GitHub Actions Brief Introduction
- GitHub Actions workflow can be used to automate the CICD for software deployments and running various stages for software development life cycle.
- As per the [documentation](https://docs.github.com/en/actions)

> GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline. You can create workflows that build and test every pull request to your repository, or deploy merged pull requests to production.

> GitHub Actions goes beyond just DevOps and lets you run workflows when other events happen in your repository. For example, you can run a workflow to automatically add the appropriate labels whenever someone creates a new issue in your repository.
> GitHub provides Linux, Windows, and macOS virtual machines to run your workflows, or you can host your own self-hosted runners in your own data center or cloud infrastructure.

## Introduction to Workflow Yaml Blocks
- GitHub action workflow consists of various component blocks,
- `on` block - In this block we'll mention what is the triggering event for the workflow. It controls when the action will run. Workflow runs when manually triggered using the UI
- `workflow_displatch` - It is the sub block inside the `on` event triggering block, in which we can specify what are the inputs needed to trigger the workflow. 
- `jobs` block - In this block we'll define the workflow actions like code building, testing and deployment to environments. A workflow run is made up of one or more `jobs` that can run sequentially or in parallel
- `steps` block - This is a sub block inside `jobs`, where each stages of job will be defined

- After adding a new workflow file in the `$REPO_HOME_PATH/.github/workflows` directory, it will be showing up in the repo `actions` tab. (As shown below) 

![TF workflow trigger](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sm7n7m3rfcaxtxp8rlcp.png)


## Workflow Yaml for Terraform AWS Pipeline
- In the `on` event block `workflow_dispatch` section, we will be adding the inputs directory path, on which we are going to run our Terraform code validation
- It is defaulted to `'aws_samples/create_ec2'`, but it can be changed while executing the `workflow` at the time of code verification.

```
name: Terraform AWS Workflow

on:
  workflow_dispatch:
    # Inputs the workflow expects.
    inputs:
      tfpath:
        description: 'TF File Path'     
        required: false
        default: 'aws_samples/create_ec2'
```

- In the `jobs` block, we need to specify the workflow runner OS and code checkout action.
- Under the steps, we are performing below tasks,
  - Installing AWS CLI and configuring in runner. We need to set the `AWS_SECRET_KEY` and `AWS_ACCESS_KEY` as Github repo secret in repo settings.
  - Setting up terraform CLI
  - Running Terraform CLI commands, init, plan, apply and destroy (apply and destroy are commented since it's demo workflow)
```
jobs:
  tf_code_check:
    name: Terraform Validation and Build
    runs-on: ubuntu-latest

    if:  ${{ inputs.tfpath }} 
    steps:
    - uses: actions/checkout@v2.5.0
    

    - name: Configure AWS Credentials Action For GitHub Actions
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        aws-region: us-west-2 
    - name: Setup Terraform CLI
      uses: hashicorp/setup-terraform@v2.0.2

    - name: Terraform init, plan and apply
      run: |
        echo `pwd`
        echo "tfpath ${{ github.event.inputs.tfpath }}"
        echo "** Running Terraform Init**"
        terraform init
        
        echo "** Running Terraform Validate**"
        terraform validate
        
        echo "** Running Terraform Plan**"
        terraform plan
        
#        echo "** Running Terraform Apply**"
#        terraform apply -auto-approve
      working-directory: ${{ github.event.inputs.tfpath }}
    - name: Terraform Destroy
      run: |
        echo "** Running Terraform Destroy**"
        terraform plan -destroy
#        terraform destroy -auto-approve
      working-directory: ${{ github.event.inputs.tfpath }}
```

- Workflow Yaml code is available in [chefgs/terraform_repo](https://github.com/chefgs/terraform_repo/blob/main/.github/workflows/tf_code_validation_aws.yml)

## Demo Video

Please see the demo video of running the [workflow here](https://github.com/chefgs/repo_images/blob/master/terraform_aws_workflow.webm)

## Conclusion
- Automating Terraform workflows for AWS is simple and effective
-  When we create a gh workflow with workflow_dispatch, it has to be pushed into `main` branch. If we try to add it on another branch, the option `run workflow` to manually triggering the workflow won't be visible. Refer the community discussion [here](https://github.com/orgs/community/discussions/25219)     

## References
- [Workflow Dispatch Inputs](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#onworkflow_dispatchinputs)
- [Jobs](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobs)
- [Terraform Market place Action](https://github.com/marketplace/actions/hashicorp-setup-terraform)
- [Terraform AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
- [AWS Creds configure](https://github.com/marketplace/actions/configure-aws-credentials-action-for-github-actions)
- [All AWS Github actions](https://github.com/aws-actions)

### Follow me on,
- [Dev](https://dev.to/chefgs)
- [GitHub](https://github.com/chefgs)
- [LinkedIn](https://www.linkedin.com/in/saravanan-gnanaguru-1941a919/)
- [Twitter](https://twitter.com/saransid)
- [gsaravanan.dev](https://gsaravanan.dev)