Search code examples
amazon-web-servicesterraformterraform-provider-awsterraspace

Reference module with multiple resources


I am trying to create an AWS route53 hosted zone and add records to it. I added the following resources to a module main.tf

resource "aws_route53_zone" "zone" {
  name = var.name
}

data "aws_route53_zone" "zone_data" {
  name = var.name

}

resource "aws_route53_record" "record" {
  zone_id = data.aws_route53_zone.zone_data.zone_id
  name    = var.record_name
  type    = var.record_type
  ttl     = var.record_ttl
  records = var.record_value
}

Then I reference that module in a stack main.py as follows:

module "route53" {
  source = "../../modules/route53"
  name   = "website.com"
  type   = "NS"
  ttl    = "30"

}

My issue is that building the stack will use the same name variable for both zone and record resources. How do I add another name to the stack module route53 for the record resource that is different from the zone resource?


Solution

  • If all you're trying to do in the module is create a zone and a record, you could use split to get the zone from the record name given. Like this:

    main.tf

    module "route53" {
      source = "./modules/route53"
      name   = "something.website.com"
      type   = "NS"
      ttl    = "30"
    }
    

    modules/route53/main.tf

    variable "name" {}
    variable "type" {}
    variable "ttl" {}
    
    resource "aws_route53_zone" "this" {
      name = split(".", var.name)[0]
    }
    
    resource "aws_route53_record" "this" {
      zone_id = aws_route53_zone.this.zone_id
      name    = var.name
      type    = var.type
      ttl     = var.ttl
      records = [var.name]
    }
    

    If however, you want multiple records in that zone, you could consider something like this, but this will depend heavily on what record configuration you're after.

    main.tf

    module "route53" {
      source = "./modules/route53"
      name   = "website.com"
    
      record_configs = {
        something = {
          type    = "A"
          records = ["192.168.0.99"]
        }
        other = {
          type    = "CNAME"
          records = ["something.website.com"]
        }
      }
    }
    

    modules/route53/main.tf

    variable "name" {}
    variable "record_configs" {}
    
    resource "aws_route53_zone" "this" {
      name = var.name
    }
    
    resource "aws_route53_record" "this" {
      for_each = var.record_configs
    
      zone_id = aws_route53_zone.this.zone_id
      name    = each.key
      type    = each.value.type
      records = each.value.records
    }