skip to Main Content

I would like to store a terraform state file in one aws account and deploy infrastructure into another. Is it possible to provide different set of credentials for backend and aws provider using environmental variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)? Or maybe provide credentials to one with environmental variables and another through shared_credentials_file?

main.tf

terraform {
    required_providers {
        aws = {
            source  = "hashicorp/aws"
            version = "=3.74.3"
        }
    }
    backend "s3" {
        encrypt = true
        bucket = "bucket-name"
        region = "us-east-1"
        key = "terraform.tfstate"
    }
}

variable "region" {
    default = "us-east-1"
}
provider "aws" { 
  region                  = "${var.region}"
}

resource "aws_vpc" "test" {
  cidr_block = "10.0.0.0/16"
}

2

Answers


  1. Yes, the AWS profile/access keys configuration used by the S3 backend are separate from the AWS profile/access keys configuration used by the AWS provider. By default they are both going to be looking in the same place, but you could configure the backend to use a different profile so that it connects to a different AWS account.

    Login or Signup to reply.
  2. Yes, and you can even keep them in separated files in the same folder to avoid confusion

    backend.tf

    terraform {
      backend "s3" {
        profile         = "profile-1"
        region          = "eu-west-1"
        bucket          = "your-bucket"
        key             = "terraform-state/terraform.tfstate"
        dynamodb_table  = "terraform-locks"
        encrypt         = true
      }
    }
    

    main.tf

    provider "aws" {
      profile                 = "profile-2"
      region                  = "us-east-1"
    }
    
    resource .......
    

    This way, the state file will be stored in the profile-1, and all the code will run in the profile-2

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search