How to get your public IP on terraform

Using HTTP

Getting your public IP on terraform using HTTP is simple, but it requires an external dependency. Online you’ll find tons of open APIs like https://www.ipify.org, https://seeip.org, https://ipinfo.io, etc, that you can use. Once you have picked one, simply HTTP GET your JSON response with hashicorp/http and parse the output appropriately.

terraform {
  required_providers {
    http = {
      source  = "hashicorp/http"
      version = "3.1.0"
    }
  }
}

data "http" "ipinfo" {
  url = "https://ipinfo.io"
}

This can be extremely useful to enable traffic between your work station and remote servers, without exposing them to the rest of the internet.

module "openvpn" {
  source  = "terraform-aws-modules/security-group/aws"
  # (...)
  ingress_with_cidr_blocks = [
    {
      from_port   = 0
      to_port     = 0
      protocol    = "-1"
      cidr_blocks = format("%s/32", jsondecode(data.http.ipinfo.body).ip)
    },
  ]
}

Feeling frisky? DNS?

If you’re feeling hipster, you might consider using DNS. This still requires an external dependency (DNS server). I don’t recommend it, but who am I to advise on this matter anyway?

terraform {
  required_providers {
    dns = {
      source = "hashicorp/dns"
      version = "3.2.3"
    }
  }
}

data "dns_a_record_set" "whoami" {
  host = "myip.opendns.com"
}

output "ip" {
    value = data.dns_a_record_set.whoami.addrs
}

This is roughly the same as running dig myip.opendns.com @resolver1.opendns.com -4 +short.

NOTE: Take into account that for the above code to work you’ll need to add a new nameserver entry in your /etc/resolv.conf, find the IP of the DNS resolver with dig, i.e. dig resolver1.opendns.com +short.

· terraform, aws