Terraform repo storing tfstate in AWS S3 bucket

2024.07.17

Create AWS S3 bucket

Create new bucket or select existing one to store tfstate

Create AWS IAM User Token

IAM > Users > %terraform user% (policy AdministratorAccess attached) > Create access key

Create terraform files

00-main.tf

provider "aws" {
  region = "us-east-1"
}

terraform {
  required_version = "~> 1.9.0"
  backend "s3" {
    bucket = "monitoring-terraform" # Name of bucket
    key    = "terraform/state/monitoring/terraform.tfstate" # Path in bucket
    region = "us-east-1"
  }
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.57.0"
    }
  }
}

Create github Workflow

Files

.github/workflows/terraform-apply.yml

name: 'Terraform apply'

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  terraform:
    runs-on: ubuntu-latest

    env:
      AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
      AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Setup Terraform
      uses: hashicorp/setup-terraform@v1
      with:
        terraform_version: 1.9.1

    - name: Terraform Init
      run: terraform init

    - name: Terraform Validate
      run: terraform validate

    - name: Terraform Plan
      run: terraform plan

    - name: Terraform Apply
      if: github.ref == 'refs/heads/main'
      run: terraform apply -auto-approve

Environment

Create environmental secret variables with values we got in IAM:

  • AWS_ACCESS_KEY_ID

  • AWS_SECRET_ACCESS_KEY

Configure local environment

If you have debian os:

Install packages

sudo apt-get update
sudo apt-get install -y gnupg software-properties-common curl unzip
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt-get update
sudo apt-get install terraform
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
./aws/install --install-dir ${HOME}/.local/aws-cli --bin-dir ${HOME}/.local/bin

Ensure, your PATH variable contents ${HOME}/.local/bin

export PATH=${HOME}/.local/bin:$PATH

Log in to AWS

aws configure --profile PROJECTNAME

AWS Access Key ID and AWS Secret Access Key for userspace you can get in IAM > Security credentials > Create access key

You can check if your credentials are ok with

aws --profile PROJECTNAME s3 ls

Profit

terraform fmt
AWS_PROFILE=PROJECTNAME terraform init
AWS_PROFILE=PROJECTNAME terraform plan
AWS_PROFILE=PROJECTNAME terraform apply

or

terraform fmt
export AWS_PROFILE=PROJECTNAME
terraform init
terraform plan
terraform apply