Pierre-Alexandre
Pierre-Alexandre

Reputation: 765

Create a S3 bucket on each AWS account created with terraform

I am using terraform to create multiple AWS accounts using aws_organizations_account. What I am now trying to do is to create a aws_S3_bucket on each new created accounts.

resource "aws_organizations_account" "this" {
  for_each  = local.all_user_ids
  name      = "Dev Sandbox ${each.value}"
  email     = "${var.manager}+sbx_${each.value}@example.com"
  role_name = "Administrator"
  parent_id = var.sandbox_organizational_unit_id
}

resource "aws_s3_bucket" "b" {
  bucket = "my-tf-test-bucket"
  acl    = "private"
}

Everything is working as expected for aws_organizations_account during my terraform apply but my S3 bucket is created inside my current AWS project while I am trying to create a S3 bucket for every new AWS account.

Upvotes: 0

Views: 357

Answers (1)

Transformer
Transformer

Reputation: 7429

Step 1: Create_terraform_s3_buckets.tf


# First configure the AWS Provider
provider "aws" {
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
  region     = var.aws_region
}

// then use the resource block and create all the buckets in the variable array
// Here setup your accounts would in the variable for e.g. My_Accounts_s3_buckets      
variable "My_Accounts_s3_buckets" {
  type = list
  default = ["Testbucket1.app", "Testbucket2.app", "Testbucket3.app"]
}

Look up the s3_bucket objectfor more help from Terraform ref. aws_s3_bucket

 // resource "aws_s3_bucket" "rugged_buckets" "log_bucket" { <- different types of options on your buckets
 resource "aws_s3_bucket" "b" {
  count         = length(var.My_Accounts_s3_buckets) // here are you 3 accounts
  bucket        = var.My_Accounts_s3_buckets[count.index]
  acl           = "private"
  region        = "us-east-1"
  force_destroy = true

 tags = {
  Name        = "My Test bucket"
  Environment = "Dev"
 }

}

Step 2: You can now automate this with the variables file.

# Make sure you keep this order

variable "My_Accounts_s3_buckets" {
  type = list
  default = ["mybucket1.app", 
             "mybucket2.app" // you can add more.. as needed                 
            ]
}

Upvotes: 1

Related Questions