How to terraform output from state file with or without jq?

643 views Asked by At

I need to read some data from the state file, to be specific, I need to import a DNS record's IP address into my terraform configuration. I have a resource aws_route53_record.dns_record that I imported from the state file.

This is the output definition:

    output "dns_record_ip" {
      value = aws_route53_record.dns_record.*.records[0]
    }

And this is the actual output:

    dns_record_ip = toset([
      "10.10.10.100",
    ])

When I try to extract only the IP as a string like this:

    terraform output -json dns_record_ip | jq -r '.[0]'

I indeed get a string:

    10.10.10.100

Is there a way to achieve this by modifying the output definition so I don't have to use jq and command line since I need to use the output value in my terraform configuration? EDIT: Needed an output value so it can be used by another module.

How can I modify this:

    output "dns_record_ip" {
      value = aws_route53_record.dns_record.*.records[0]
    }

so the value of dns_record_ip is actually 10.10.10.100?

ps: edited to avoid confusion

1

There are 1 answers

0
Martin Atkins On

If you know that there will only be at most one instance of aws_route53_record.dns_record -- for example, if you have a count expression whose value can only be zero or one -- then you can define the output to be the single element from that list using the one function, like this:

output "dns_record_ip" {
  value = one(one(aws_route53_record.dns_record[*].records))
}

This is a slightly more confusing use of one than normal because you seem to have two different one-element collections here: the aws_route53_record.dns_record resource as a whole has one instance, and then its records attribute is a one-element set. Using one twice like this should therefore first peel out the one set of records and then the one record from that set.

You should then be able to get this raw string, without any need for jq, using:

terraform output -raw dns_record_ip

If there is a possibility of this result containing more than one element in some cases then there isn't really any alternative to returning a collection, and so you would need to use jq in that case because JSON is the only supported machine-readable format for an output value that cannot convert to a string.