Search code examples
terraformterraform-provider-aws

How to import Route53 record that contains underscores


I have an existing Route53 record that I'm attempting to import. Example of the record: 50200._dkey.mydomain.com

I create the resource like so:

resource "aws_route53_record" "50200_dkey_txt" {
  zone_id = aws_route53_zone.mydomain_com.zone_id
  name = "50200._dkey.mydomain.com"
  type = "TXT"
  ttl = "300"
  records = ["text_record_contents"]
}

Then, I run the import:

terraform import module.route53.aws_route53_record.50200_dkey_txt Z0N3ID0FZ0NE_50200._dkey.mydomain.com_TXT

I'm greeted with the following error:

╷
│ Error: Attribute name required
│ 
│   on <import-address> line 1:
│    1: module.route53.aws_route53_record.50200_dkey_txt
│ 
│ Dot must be followed by attribute name.
╵

I'm assuming the underscore in the record is the culprit. If I'm correct in assuming so, is there a way to escape the underscore character or format it in such way to make terraform read it in literal form? I attempted to wrap it in single quotes, but received the same error.


Solution

  • Terraform does not allow a resource name that starts with a digit, because when referring to resources elsewhere in the module and on the command line Terraform (similar to many other languages) treats a digit as the start of a number, rather than as the start of a name.

    Normally Terraform would catch this when parsing your configuration, but I think because you are using terraform import as your first command to run here it's the command line parsing that is coming first, and therefore unfortunately raising a less helpful error.

    This is what other Terraform commands would've shown, due to the configuration being invalid:

    ╷
    │ Error: Invalid resource name
    │ 
    │   on example.tf line 1, in resource "aws_route53_record" "50200_dkey":
    │    1: resource "aws_route53_record" "50200_dkey" {
    │ 
    │ A name must start with a letter or underscore and may contain only letters,
    │ digits, underscores, and dashes.
    ╵
    

    The solution then is to change the resource name to be a valid name, such as by adding some letters to the start of it as a prefix:

    resource "aws_route53_record" "txt_50200_dkey" {
      # ...
    }
    

    Then when you run terraform import you should specify the new resource name, but you should be able to keep the same remote identifier (the second argument) so that Terraform will bind the given remote object to the given local address:

    terraform import "module.route53.aws_route53_record.txt_50200_dkey" "Z0N3ID0FZ0NE_50200._dkey.mydomain.com_TXT"
    

    (I'm actually not sure how aws_route53_record in particular interprets its "remote ID" strings, so I've just copied what you tried verbatim here. With the invalid resource name fixed this may expose a new error about the ID string, but I probably won't know the answer to that one if so. 😬)