Deploy Github code using Terraform and Github Actions: working example

Elvis Ciotti
2 min readApr 12, 2023

In your repository, create the following files

# .github/workflows/terraform.yml

name: 'Terraform'

on:
push:
branches: [ "main" ]

permissions:
contents: read

jobs:
terraform:
name: 'Terraform deploy ...'
runs-on: ubuntu-latest
environment: production
defaults:
run:
shell: bash
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Terraform
uses: hashicorp/setup-terraform@v1
- name: Terraform Init
run: terraform init
- name: Terraform Format
run: terraform fmt -check
- name: Terraform Plan
run: terraform plan -var="region=${{ secrets.AWS_REGION }}" -var="access_key=${{ secrets.AWS_ACCESS_KEY }}" -var="secret_key=${{ secrets.AWS_SECRET_KEY }}"
- name: Terraform Apply
# if: github.ref == 'refs/heads/"main"' && github.event_name == 'push'
run: terraform apply -auto-approve -var="region=${{ secrets.AWS_REGION }}" -var="access_key=${{ secrets.AWS_ACCESS_KEY }}" -var="secret_key=${{ secrets.AWS_SECRET_KEY }}"

# terraform.tf

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0.0"
}
# ... more there

required_version = "~> 1.0"
}

variable "region" {
type = string
}
variable "access_key" {
type = string
}
variable "secret_key" {
type = string
}

provider "aws" {
region = var.region
access_key = var.access_key
secret_key = var.secret_key
}

# ... add resources to create here

Repository settings -> Secrets and variables

Those are needed by the terraform command expecting variables in the environment

At every push, you’ll see the following in the “Actions tab”

--

--

Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://www.linkedin.com/in/elvisciotti