Search code examples
javascriptamazon-web-servicesterraformamazon-route53

is there a way to create route53_zone and apply its zone_id to records at the same time in terraform?


I'm very new to coding and terraform.

I was trying to write every resource I needed to .tf file

while doing so, I

Terraform plan

and got an error

│ Error: no matching Route53Zone found
│
│   with data.aws_route53_zone.<name>,
│   on <filename>.tf line 70, in data "aws_route53_zone" "<name>":
│   70: data "aws_route53_zone" "<name>" {

And this is what I wrote

resource "aws_route53_zone" "example" {
    name       = "example.com"
    comment    = "eg-example"

    tags= {
        Name = "example.com"
    }
}

resource "aws_acm_certificate" "eg-example-acm-domaincert" {
    domain_name               = "*.example.com"
    validation_method         = "DNS"
    tags = {
      name = "eg-example-acm-domaincert"
      }
}

resource "aws_route53_record" "cname-example" {
    zone_id = data.aws_route53_zone.example.zone_id
    name    = "cname.example.com"
    type    = "CNAME"
    records = ["cname-example-alb-ext-1111111111.region.elb.amazonaws.com"]
    ttl     = "300"

}

data "aws_route53_zone" "example" {
  name         = "example.com."
  private_zone = true
}

resource "aws_acm_certificate_validation" "eg-example-acm-domaincert" {
  certificate_arn         = "arn:aws:acm:**********************"
  validation_record_fqdns = ["*****************************.example.com"]
}

the code was not so different from this.

I really don't have any idea besides creating a zone on the AWS console.

is there any other way?

I hope my explanation makes sense to you.


Solution

  • Get rid of your call to data and just use the resource:

    aws_route53_zone.example.zone_id

    Use data when you're retrieving a resource you've previously created (from another Terraform project, for example).

        
    resource "aws_route53_record" "cname-example" {
        zone_id = aws_route53_zone.example.zone_id // no need for data.
        name    = "cname.example.com"
        type    = "CNAME"
        records = ["cname-example-alb-ext-1111111111.region.elb.amazonaws.com"]
        ttl     = "300"
    
    }

    Run terraform validate and terraform plan.

    Good luck!