This is a example on how to build and manage an AWS multi account architecture using Terraform workspaces. The proposal focus only in segment and relate an account to a workspace.
There wasn’t aim to modularize, treat security issues or save the state on a remote backend, just present a proposal for multi-account issue.
There is a way to test it in local environment before applying to an AWS infrastructure using Localstack.
As OpenTofu is an opensource alternative to Terraform, I will use it. To know more about Terraform licensing, check here.
This example uses the Docker Compose solution to run Localstack. Neverthless there is other ways to run it, jus check the official documentation for alternatives.
All the documentation was written running on Localstack, but it was tested on multiple accounts as well. Just adjust your ~/.aws/config and ~/.aws/credentials files with your credentials and it should work.
There is a docker-compose.yaml file in repository ready to use, with 2 instances of the Localstack running in different ports. It was selected this approach for simplicity, to isolate the accounts and simulate different environments. The instances were named as localstack-dev and localstack-uat.
To put up the services just run docker-compose up -d --build
.
Adjust your ~/.aws/config file to have 2 profiles (accounts) as defined in Localstack instances.
PS. May be a good idea to backup the file before change it. ;-)
[profile dev]
region=us-east-1
output=json
endpoint_url = http://localhost:4566
[profile uat]
region=us-east-1
output=json
endpoint_url = http://localhost:4567
Then do the same for the ~/.aws/credentials. The keys are not important for the test, because we are not testing the auth features (the validation was disabled on Terraform code).
Remember of the backup :-)
[dev]
aws_access_key_id=test
aws_secret_access_key=test
[uat]
aws_access_key_id=test
aws_secret_access_key=test
At this point you may be able to run aws cli commands to test the Localstack service.
Terraform uses the default workspace