Home > Software engineering >  How to store terraform state in one account and apply changes in another account using AWS?
How to store terraform state in one account and apply changes in another account using AWS?

Time:06-19

I have set up an AWS Organization using ControlTower. I created a user for myself that has AWSAdministratorAccess for the 2 accounts below.

  • Root
    • Operations Group (Organizational Unit)
      • Infrastructure Account (AWS Account - 111)
    • Dev (Organizational Unit)
      • DEV Account (AWS Account - 222)

I am starting simple for now to get a good base foundation while building up the organization. One thing I have read is that we should be storing our terraform state files in the Infrastructure Account while doing our operation changes on the DEV Account.

How can I do that in terraform? I am a bit lost because I am using AWS SSO and can't figure out what to place for the role_policy_arn.

Here is an example code:

terraform {
  backend "s3" {
    bucket = "terraform-infrastructure"
    key    = "dev/sqs/terraform.tfstate"
    region = "us-east-1"
    assume_role_policy_arns = ["<what do I put here>"]
  }

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region = "us-east-1"
  allowed_account_ids = ["222"]
}

Also, is there anything I need to do on the S3 side? I am assuming no. If I can assume the role of AWSAdministratorAccess for Infrastructure Account and store the terraform state there and assume the role of AWSAdministratorAccess for DEV Account and apply my changes, then I don't need to mess with S3 permission to allow cross account publications.

CodePudding user response:

Consider adding the profile configuration to the backend block. The associated profile will need to be setup in your ~/.aws/config file. Also, you can add the profile configuration to the provider block to similarly use the AWS CLI profiles. Using the profile configurations and setting up AWS CLI using profiles with correct accounts and roles should enable you to accomplish what your intending to do.

CodePudding user response:

I suggest you reading this documentation https://www.terraform.io/language/settings/backends/s3#delegating-access, it will clarify your doubts.

  • Related