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”

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet

Write a response