Terraform: Managing resources in multiple AWS accounts

Sometimes i have to provision and maintain resources referencing each other in different AWS account. Such scenario can be automated with terraform’s configurable providers. All providers will share the same terraform state and will be able to access resource IDs and generated ARNs.

To implement such solution you have to perform 2 steps:

  • Register terraform providers and configure them with access keys
  • Tell terraform in which particular resource should be created by assigning a corresponding provider
# Configure workload zone AWS provider 
provider “aws” {
alias = “main” # provider's name
region = “${var.aws_region}”
access_key = “${var.aws_access_key}”
secret_key = “${var.aws_secret_key}”
}
# Configure service zone AWS provider
provider “aws” {
alias = “service” # provider's name
region = “${var.service_aws_region}”
access_key = “${var.service_aws_access_key}”
secret_key = “${var.service_aws_secret_key}”
}
# Create EC2 instance in workload zone
resource "aws_instance" "app" {

# tell terraform to create app instance in main account
provider = "aws.main"
    ami           = "${var.ubuntu_ami}"
subnet_id = "${aws_subnet.private_a.id}"
    ....
}
# Create Route53 entry in service zone
resource "aws_route53_record" "mongo_3" {
# tell terraform to create a DNS entry
# for the app instance in service account
provider = "aws.service"
    zone_id = "${var.service_hosted_zone_id}"
name = "app"
type = "A"
records = ["${aws_instance.app.private_ip}"]
}