I've got a couple of EC2 instances managed by Terraform, with public IP addresses in a VPC.

With each Terraform run, I'm updating DNS records based on those public IPs.

I don't need these instances on all the time though, and when I shut them down, they of course lose their public IP address.

At first this was causing associate_public_ip_address to become false, and Terraform wanted to recreate the instances. lifecycle.ignore_changes solves this:

resource "aws_instance" "instance1" {
  associate_public_ip_address = true

  lifecycle {
    ignore_changes = ["associate_public_ip_address"]

resource "cloudflare_record" "record1" {
  domain = "example.com"
  name   = "server1.example.com"
  value  = "${aws_instance.instance1.public_ip}"
  type   = "A"

But... the public_ip attribute also becomes blank ;). This causes an attempted update to the A record, which fails because you can't set a blank record.

So, I'm trying to work out a solution. I could use elastic IPs, which I might end up resorting to, but I'd ideally like to avoid that if I can. My next thought was... is there any way I could use ignore_changes conditionally, and thus ignore changes to the DNS record's value if it is blank?

Are there any other solutions you can recommend?


Maybe you could use "count" attribute for this?

resource "cloudflare_record" "record1" {
    count = ${aws_instance.instance1.public_ip == "" ? 0 : 1}"
  • Thanks for the suggestion. I should clarify - I do keep the instances active, but just shut them down when I'm not using them. So unfortunately this wouldn't work as to Terraform, the instances still exist. I'll edit my post to clarify this. – Tim Malone Jul 15 '18 at 21:26
  • Actually - I do apologise - I read your answer in a hurry and completely misinterpreted it!! I think this should work actually and I’m not sure why I didn’t try it. Will give it a go shortly! – Tim Malone Jul 16 '18 at 21:13
  • Great, hope it works for you! – Yekta Leblebici Jul 17 '18 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.