Guides

Aws acm dns verification using route53 and terraform

Abdelfattah Hilmi
#Cloud#Devops#SRE#Terraform

Certficate Quotas:

Set up terraform environment for dev:

First- setup creds:

export  AWS_ACCESS_KEY_ID="ur access key ID"
export AWS_SECRET_ACCESS_KEY="ur access secret"
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~>4.16"
    }
  }
  required_version = ">= 1.2.0"
}

provider "aws" {
  region = "eu-west-2"
}

How to create a route53 record:

#adding a record to existing hosted zone

data "aws_route53_zone" "hosted_zone" {
  name = var.domain_name
}


resource "aws_route53_record" "site_domain" {
  zone_id = data.aws_route53_zone.hosted_zone.zone_id
  name    = var.record_name
  type    = "A" # specify any record type 
  ttl     = 300
  records = ["valid ipv4 address because the type is `A` record"]
}
variable "domain_name" {
  default     = "{your domain name}"
  description = "domain name variable"
  type        = string
}
variable "record_name" {
  default     = "{your record name}"
  description = "record name variable"
  type        = string
}

Request certificates and validate them using DNS in route53:

the hcl code is the following:

# get the data about route53 zone 
data "aws_route53_zone" "route53_zone" {
  name         = "abdelhilmi.com"
  private_zone = false
}

#Request a certificate for our domain name from ACM and validate it using dns in route53
resource "aws_acm_certificate" "acm_certificate" {
  domain_name               = var.main_subdomain
  subject_alternative_names = var.subdomain_alternatives
  validation_method         = "DNS"

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_route53_record" "route53_record" {
  for_each = {
    for dvo in aws_acm_certificate.acm_certificate.domain_validation_options : dvo.domain_name => {
      name   = dvo.resource_record_name
      record = dvo.resource_record_value
      type   = dvo.resource_record_type
    }
  }

  allow_overwrite = true
  name            = each.value.name
  records         = [each.value.record]
  ttl             = 60
  type            = each.value.type
  zone_id         = data.aws_route53_zone.route53_zone.zone_id
}

resource "aws_acm_certificate_validation" "acm_certificate_validation" {
  certificate_arn         = aws_acm_certificate.acm_certificate.arn
  validation_record_fqdns = [for record in aws_route53_record.route53_record : record.fqdn]
}
foo@bar:~$ terraform fmt
foo@bar:~$ terraform validate 
foo@bar:~$ terraform apply

#delete everything created
foo@bar:~$ terraform destroy
← Back to Blog