Search code examples
dnsterraformcnamelinode

How to point CNAME to a hostname using terraform


I am adding a CNAME record using terraform and I want to point it to hostname I created using terraform on linode.

This is my main.tf

terraform {
  required_providers {
    linode = {
      source = "linode/linode"
      version = "1.16.0"
    }
  }
}

provider "linode" {
    token = "some_secret_token"
}

resource "linode_instance" "example_instance" {
    label = "example_instance_ubuntu-eu-west"
    image = "linode/ubuntu20.04"
    region = "eu-west"
    type = "g6-nanode-1"
    root_pass = "testing@linode"
}

resource "linode_domain" "example_domain" {
  domain   = "example.mydomain.com"
  soa_email= "[email protected]"
  type     = "master"
}

resource "linode_domain_record" "example_domain_record" {
  domain_id  =  linode_domain.example_domain.id
  name       = "example.mydomain.com"
  record_type= "CNAME"
  target     = linode_instance.example_instance.label
  ttl_sec    = 300
}

terrafomr plan results in

linode_domain.example_domain: Refreshing state... [id=1753447] linode_instance.example_instance: Refreshing state... [id=33094611]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:

  • create

Terraform will perform the following actions:

  # linode_domain_record.example_domain_record will be created
  + resource "linode_domain_record" "example_domain_record" {
      + domain_id   = 1753447
      + id          = (known after apply)
      + name        = "example.mydomain.com"
      + record_type = "CNAME"
      + target      = "example_instance_ubuntu-eu-west"
      + ttl_sec     = 300
    }

Plan: 1 to add, 0 to change, 0 to destroy.

But terraform apply errors:

linode_domain_record.example_domain_record: Creating...
╷
│ Error: Error creating a Linode DomainRecord: [400] [target] You have entered an invalid target. It must be a valid hostname.; [name] Invalid hostname 
│ 
│   with linode_domain_record.example_domain_record,
│   on main.tf line 28, in resource "linode_domain_record" "example_domain_record":
│   28: resource "linode_domain_record" "example_domain_record" {
│ 
╵

but example_instance_ubuntu-eu-west does exist in the my linodes


Solution

  • Per @mark-b's comment, you may want to consider using an A(ddress) record type rather than CNAME to reference the linode.

    As long as the Linode has an accessible public IPv4 address (replace ADDR below with the linode's public IP), you can:

    resource "linode_domain_record" "example_domain_record" {
      domain_id  =  linode_domain.example_domain.id
      name       = "example.mydomain.com"
      record_type= "A"
      target     = ADDR
      ttl_sec    = 300
    }
    

    See: linode_domain_record and specifically the documentation for record_type

    It's unlikely but if the instance has an IPv6 address then you'll want to use AAAA