How to programmatically use your public Internet IP address in Terraform?

Programmatically use your public IP in Terraform as source IP for AWS Security Rules

During testing of HashiCorp Terraform plans, sometimes there is a need to create firewall rules that use your current public Internet IP address, for example for SSH access to the created instances.


  • 2020 Jun 29: Upgraded to Terraform 0.12

There is an easy way to programmatically obtain the IP address using a Terraform External Data Source.

Create a shell script that obtains the IP address and returns the value in a JSON object.

set -e
INTERNETIP="$(dig +short"
echo $(jq -n --arg internetip "$INTERNETIP" '{"internet_ip":$internetip}')

Call the external data source and use the output in a firewall rule. The example in shows how to use the public IP address in an AWS security rule created by Terraform to allow SSH access.

data "external" "whatismyip" {
  program = ["/bin/bash" , "${path.module}/"]
resource "aws_security_group_rule" "allow_ssh_from_my_ip" {
 type = "ingress"
 from_port = 22
 to_port = 22
 protocol = "tcp"
 cidr_blocks = [format("%s/%s",data.external.whatismyip.result["internet_ip"],32)]
 security_group_id = "sg-123456"

Make sure to install jq utility and also make executable using:

sudo apt-get install jq
chmod 764

Since you are now using an additional data source, the External Data Source, initialize Terraform using:

terraform init

See more Terraform and Ansible examples:

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

0 0 vote
Article Rating

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments

IT Wonder Lab - Best Practices for the Cloud

ansible-aws-ec2-terraform-tags - ansible-aws-ec2-terraform-tags-ec2.png

How to use Ansible and Terraform together?

This Ansible AWS tutorial shows how to use Ansible and its dynamic inventory to provision the software and configuration of infrastructure that has been created with Terraform.