author avatar

soniya.rayabagi

Tue Jul 09 2024

Automating Terraform with GitHub Actions:
I learned how to automate Terraform linting, planning, and applying using GitHub Actions. This helps ensure code is always in good shape and deployed correctly. Here’s a step-by-step guide to set it up:
Steps:
• Create a .github/workflows/terraform.yml file in your repository. This single file defines the entire workflow for GitHub Actions.
• Set up the workflow to trigger on pull requests and pushes to the main branch. This ensures that the Terraform configuration is checked and applied automatically whenever changes are made.


name: Terraform CI/CD

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  terraform:
    name: Terraform Lint, Plan, and Apply
    runs-on: ubuntu-latest

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

    - name: Set up Terraform
      uses: hashicorp/setup-terraform@v2
      with:
        terraform_version: 1.8.3

    - name: Terraform Init
      run: terraform init

    - name: Terraform Format
      run: terraform fmt -check

    - name: Terraform Validate
      run: terraform validate

    - name: Terraform Plan
      run: terraform plan

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


Single Workflow File : By using a single .github/workflows/terraform.yml file, I streamline the CI/CD process, making it easier to manage and maintain.
Checkout Repository : The actions/checkout@v2 step checks out the repository so that the workflow has access to the Terraform configuration files.
Set up Terraform : The hashicorp/setup-terraform@v2 action sets up the specified version of Terraform on the runner.
Terraform Init: The terraform init command initializes the working directory containing Terraform configuration files.
Terraform Format : The terraform fmt -check command ensures that the Terraform configuration files are properly formatted. This helps maintain a consistent coding style.
Terraform Validate : The terraform validate command checks the syntax and configuration of the Terraform files to ensure they are valid.
Terraform Plan : The terraform plan command creates an execution plan, showing what actions Terraform will take to reach the desired state. This step allows you to review changes before they are applied.
Terraform Apply : The terraform apply -auto-approve command applies the changes required to reach the desired state of the configuration.
#devops #Terraform #GitHubActions #HashiCorp