2
votes

My goal is to create a Terraform Module which creates a Child AWS account and creates a set of resources inside the account (for example, AWS Config rules).

The account is created with the following aws_organizations_account definition:

resource "aws_organizations_account" "account" {
  name  = "my_new_account"
  email = "[email protected]"
}

And an example aws_config_config_rule would be something like:

resource "aws_config_config_rule" "s3_versioning" {
  name        = "my-config-rule"
  description = "Verify versioning is enabled on S3 Buckets."

  source {
    owner             = "AWS"
    source_identifier = "S3_BUCKET_VERSIONING_ENABLED"
  }

  scope {
    compliance_resource_types = ["AWS::S3::Bucket"]
  }
}

However, doing this creates the AWS Config rule in the master account, not the newly created child account.

How can I define the config rule to apply to the child account?

1
You might benefit from this answer: serverfault.com/questions/929745/… But it sounds like what you are wanting to do will be very very painful, I'd advice against it.Derrops

1 Answers

2
votes

So, I was actually able to achieve this by defining a new provider in the module which assumes the OrganizationAccountAccessRole inside the newly created account.

Here's an example:

// Define new account
resource "aws_organizations_account" "my_new_account" {
  name  = "my_new_account"
  email = "[email protected]"
}

provider "aws" {
  /* other provider config */
  assume_role {
    // Assume the organization access role
    role_arn = "arn:aws:iam::${aws_organizations_account.my_new_account.id}:role/OrganizationAccountAccessRole"
  }
  alias = "my_new_account"
}

resource "aws_config_config_rule" "s3_versioning" {
  // Tell resource to use the new provider
  provider = aws.my_new_account

  name        = "my-config-rule"
  description = "Verify versioning is enabled on S3 Buckets."

  source {
    owner             = "AWS"
    source_identifier = "S3_BUCKET_VERSIONING_ENABLED"
  }

  scope {
    compliance_resource_types = ["AWS::S3::Bucket"]
  }
}

However, it should be noted that defining the provider inside the module leads to a few quirks, notably once you source this module you cannot delete this module. If you do it will throw a Error: Provider configuration not present since you will have also removed the provider definition.

But, if you don't plan on removing these accounts (or are okay with doing it manually when needed) then this should be good!