'Terraform AWS iam role AlreadyExists error

i have few questions about using aws with terraform.

I'm using milliHQ/next-js/aws (https://registry.terraform.io/modules/dealmore/next-js/aws/latest) for deploy nextjs project to aws.

I has applied terraform project in my local mac successfully, and i want to build continuous integration on my github project for deploying.

I referenced this repository(https://github.com/milliHQ/terraform-aws-next-js/tree/main/examples/with-custom-domain)

the github action code is below

name: Develop Branch Build and Deploy
on:
  push:
    branches:
      - develop

jobs:
  deployment:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout source code
        uses: actions/checkout@master
        with:
          ref: develop

      - name: Install dependencies
        run: yarn install --frozen-lockfile

      - name: Build for Terraform
        run: yarn tf-next

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ap-northeast-2

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

      - name: Terraform Initialize
        run: terraform init

      - name: Terraform Plan
        run: terraform plan -no-color

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

and i got error below

github action error



Solution 1:[1]

This error is come from the Terraform code itself.

Terraform will create a tfstate file when you create the resources in the first time, and Terraform will use it to detect which resources need to create more, modify or delete. I don't see the backend config in the repo so each time you run terraform apply, Terraform will know it as creating new resources and that's how the error appear.

You can add this block in the main.tf file

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

terraform {
  backend "s3" {
    encrypt = true
    region  = "us-west-1"
    bucket  = "Bucket-to-store-state"
    key     = "location-of-state-file"
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ash Blake