Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over aws provider to create ressources in every aws account

Tags:

terraform

I have a list of objects in Terraform called users and the structure is the following:

variable "accounts" {
  type = list(object({
    id       = string #used in assume_role
    email   = string
    is_enabled = bool
  }))
}

What I am trying to achieve now is to create a simple S3 bucket in each of those AWS accounts (if the is_enabled is true). I was able to do it for a single account but I am not sure if there is a way to loop over a provider?

Code for a single account - main.tf

provider "aws" {
  alias = "new_account"
  region = "eu-west-3"

  assume_role {
    role_arn     = "arn:aws:iam::${aws_organizations_account.this.id}:role/OrganizationAccountAccessRole"
    session_name = "new_account_creation"
  }
}

resource "aws_s3_bucket" "bucket" {
  provider = aws.new_account

  bucket = "new-account-bucket-${aws_organizations_account.this.id}"
  acl    = "private"
}  
like image 223
Pierre-Alexandre Avatar asked Jan 22 '26 23:01

Pierre-Alexandre


1 Answers

You need to define one provider for each aws account you want to use:

  1. Create a module (i.e. a directory), where your bucket configuration lives:
    ├── main.tf
    └── module
        └── bucket.tf
  1. bucket.tf should contain the resource definition: resource "aws_s3_bucket" "bucket" {...}
  2. In main.tf , define multiple aws providers and call the module with each of them:
provider "aws" {
  alias  = "account1"
  region = "eu-west-1"
  ...
}
provider "aws" {
  alias  = "account2"
  region = "us-west-1"
  ...
}

module "my_module" {
  source = "./module"
  providers = {
    aws.account1 = aws.account1
    aws.account2 = aws.account2
  }
}

I guess you could also get fancy by creating a variable containing the providers, and pass it to the module invocation (you could probably also use a filter on the list to take into account the is_enabled flag)

More details about providers: https://www.terraform.io/docs/language/modules/develop/providers.html

like image 138
aherve Avatar answered Jan 27 '26 01:01

aherve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!