Skip to content

Set up a GitHub Actions workflow to automatically deploy AWS infrastructure using Terraform

rajiv-njit edited this page Nov 11, 2023 · 8 revisions

let's break down the steps for setting up a GitHub Actions workflow to automatically deploy AWS infrastructure using Terraform. This assumes that you already have a basic understanding of Terraform, an AWS account, and a GitHub repository.

Step 1: Clone Your Repository

First, make sure you have your project on GitHub. If not, create a new repository and clone it to your local machine.

git clone https://github.com/yourusername/terraform-aws-githubactions-devops.git cd terraform-aws-githubactions-devops

Step 2: Create Terraform Configuration

Write your Terraform configuration files (main.tf, variables.tf, etc.) to define your AWS infrastructure. Ensure your Terraform files are in a directory, for example, terraform/.

Step 3: Set Up AWS Credentials

In GitHub Actions, you need to set up AWS credentials securely. You can use GitHub Secrets for this.

  • Go to your GitHub repository.
  • Navigate to "Settings" > "Secrets" > "New repository secret."
  • Name the secret AWS_ACCESS_KEY_ID and add your AWS access key.
  • Name the secret AWS_SECRET_ACCESS_KEY and add your AWS secret key.

Step 4: Create GitHub Actions Workflow

Create a new file in your repository under the path .github/workflows/terraform.yml. This file will define your GitHub Actions workflow.

Here's a basic example:

name: Terraform Deploy on: push: branches: - main jobs: terraform: runs-on: ubuntu-latest

`steps:`
  `- name: Checkout Repository`
    `uses: actions/checkout@v2`

  `- name: Set up Terraform`
    `uses: hashicorp/setup-terraform@v1`
    `with:`
      `terraform_version: 1.0.0`

  `- name: Terraform Init`
    `run: terraform init terraform/`

  `- name: Terraform Plan`
    `run: terraform plan -out=tfplan terraform/`

  `- name: Terraform Apply`
    `run: terraform apply -auto-approve tfplan terraform/`

This workflow triggers on pushes to the main branch. It checks out the repository, sets up Terraform, initializes Terraform, plans the deployment, and then applies it.

Step 5: Commit and Push

Commit your changes and push them to your GitHub repository:

git add .github/workflows/terraform.yml git commit -m "Add GitHub Actions workflow for Terraform" git push origin main

Step 6: Monitor GitHub Actions

Go to the "Actions" tab on your GitHub repository to monitor the progress of your workflow. You should see your Terraform workflow running.

That's it! You've set up a basic GitHub Actions workflow to automatically deploy AWS infrastructure using Terraform.

As you become more comfortable, you can customize the workflow to suit your specific needs, integrate additional checks, and handle more advanced scenarios.

Clone this wiki locally