Run cURL and capture output to use

Hello,

Newbie on terraform.
How to run a curl command and capture the output and then eventually use it?
I am trying to create EC2 instances and assign RDP rule from my home IP. Now my home IP is dynamic. I found this URL which gives IP in text format: https://api.ipify.org

This is my security group block:
resource “aws_security_group” “dc_securitygroup” {
name = “dc_securitygroup”
description = “This security group will control Domain Controllers”
vpc_id = aws_vpc.perf_vpc.id
ingress {
from_port = 0
to_port = 0
protocol = “-1”
cidr_blocks = [var.vpc_cidr]
}
How to point my home IP in the cidr_blocks segment?

ingress {
from_port = 3389
to_port = 3389
protocol = "tcp"
cidr_blocks = [<<homeIP>>]
}

Hi @Sabrthor,

There is a Terraform provider called http which has a data source of the same name that can retrieve data from an arbitrary HTTP or HTTPS URL:

data "http" "ip_address" {
  url = "https://api.ipify.org/"
}

locals {
  ingress_ip_address = trimspace(data.http.ip_address.body)
}

I included the local value above to trim off any trailing newlines or other whitespace this API might return, although it might not be necessary if the API is documented to return just the IP address and no other whitespace characters. You could then use local.ingress_ip_address to use that result elsewhere in the configuration.

I would typically caution against this sort of context-specific configuration, because it means that each time you run Terraform in a new location it can “break” the setup for another location. However, your reference to home IP addresses suggests that you’re working alone on a personal project, so that concern won’t apply here… just something to keep in mind if you encounter a similar need in a project where multiple people in different locations may be collaborating: in that case you’d generally want to find a solution to allow all of them access simultaneously, rather than only the person who most recently ran terraform apply.

1 Like

Thank you very much. This worked out great! And yes, I agree with your assessment where scoping to dynamic IP wont be a fruitful venture in real world. Probably, it would make more sense to scope it to corporate VPN IP. However, thanks again.