简体   繁体   中英

Cross-account subdomain/hosted zone delegation in Route 53 with Terraform

I have two environments and two AWS accounts: dev and prod. Hence, I have two hosted zones:

  • dev.example.com in the dev account
  • example.com in my prod account

In order to successfully route traffic to my dev.example.com subdomain, I need to delegate to my top-level domain (TLD) with a name server record in my TLD's hosted zone. Eg,

dev.example.com NS Simple [ns-1960.awsdns-22.co.uk. ns-188.awsdns-20.com. ns-208.awsdns-37.net. ns-1089.awsdns-01.org.]

In Terraform code, I would define the two hosted zones as such:

resource "aws_route53_zone" "top_level_domain" {
  count = var.env == "prod" ? 1 : 0

  name = "example.com"

  tags = {
    name = "Hosted Zone for top-level domain in production"
    env  = var.env
  }
}

resource "aws_route53_zone" "subdomain" {
  count = var.env == "prod" ? 0 : 1

  name = "dev.example.com"

  tags = {
    name = "Hosted Zone for ${var.env} environment"
    env  = var.env
  }
}

In the interests of keeping everything codified, I would like to be able to define my delegation record in Terraform configuration. Eg,

resource "aws_route53_record" "subdomain_delegation" {
  count = var.env == "prod" ? 1 : 0

  zone_id = aws_route53_zone.top_level_domain.zone_id
  name    = "dev.example.com"
  type    = "NS"
  ttl     = 300
  records = [
    aws_route53_zone.subdomain.name_servers
  ]
}

The issue lies in the aws_route53_zone.subdomain resource not existing in my Terraform state for the prod environment (and so aws_route53_zone.subdomain.name_servers ) cannot be found.

Is there an elegant way to solve this? Or is this just a fact of life if one chooses to use AWS accounts for physical environment separation?

Update

The folder structure for my Terraform configuration roughly resembles:

dns/ (Terraform module)
dev/ (makes use of module)
prod/ (makes use of module)

The approach I'm currently using is to have two providers .

I have a master IAM user which can assume role in sub accounts.

That way - in one terraform script - I can target some actions to the root account alias, then other actions can be targeted to the sub-account alias.

So this allows some sharing of state between multiple accounts within one terraform module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM