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

Obtain your public IP address and use it in Terraform to create AWS Security Rules.

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.

Updates:

  • 2020 Jun 29: Upgraded to Terraform 0.12
  • 2020 Oct 19: Set IPV4 switch -4 in dig command as suggested by Reque.

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.

whatismyip.sh

#!/bin/bash
...
set -e
INTERNETIP="$(dig +short myip.opendns.com @resolver1.opendns.com -4)"
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 aws_security_group_rules.tf shows how to use the public IP address in an AWS security rule created by Terraform to allow SSH access.

aws_security_group_rules.tf

data "external" "whatismyip" {
  program = ["/bin/bash" , "${path.module}/whatismyip.sh"]
}
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 whatismyip.sh executable using:

sudo apt-get install jq
chmod 764 whatismyip.sh

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

terraform init

See more Terraform and Ansible examples:

terraform-aws-ec2-rds-basic-free - ITWL_AWS_Terraform_VPC_WP_Security1.png
Table of Contents
Primary Item (H2)Sub Item 1 (H3)Sub Item 2 (H4)
Sub Item 3 (H5)
Sub Item 4 (H6)

Related Cloud Tutorials

AWS Security Groups’ Best Practices
AWS Security Groups are virtual firewalls that control inbound and outbound traffic to and from Amazon Web Services (AWS) resources, such as EC2 and RDS instances.
AWS and Terraform Naming Best Practices
Terraform and AWS resource naming should follow a company standard. Each company has different requirements and the standard should be adjusted.
How To Debug Terraform
Enable Terraform debug Terraform uses the value from the environment variable TF_LOG to define the LOG level. Available values are TRACE, DEBUG, INFO, WARN or ERROR. Additionally, you can specify a destination file for the log by setting the environment variable TF_LOG_PATH to the full path of the desired destination. Set the debug variables and […]
AWS Tagging Best Practices
Effective infrastructure resource tagging can greatly improve management, IaC, monitoring and cost visibility in AWS.
How to Deploy Applications in Kubernetes using Terraform
How to publish multiple replicas of an Application (from the Docker Registry) and create a NodePort in Kubernetes using Terraform (in 10 seconds)
Terraform logo
HCL
HashiCorp Configuration Language HCL is a domain-specific language developed by HashiCorp, a company known for its infrastructure automation tools such as Terraform, Vault, Consul, and Nomad. HCL is designed specifically for writing configuration files that define infrastructure components and their settings. It is used in HashiCorp’s suite of tools to create and manage infrastructure as […]
AWS Terraform module
IaC
Infrastructure as Code IaC is an approach to managing and provisioning computing infrastructure through machine-readable code and automation, rather than manual processes. In IaC, infrastructure is defined, configured, and managed using code, which can be version-controlled and treated like any other software application. IaC involves: IaC provides several benefits, including improved efficiency, reduced manual errors, […]
AWS S3
AWS S3, is a highly scalable and durable object storage used for data storage, backup, content distribution, data archiving, and as a foundation for building cloud-native applications.
AWS EC2
Amazon Elastic Compute Cloud, is a web service offered by Amazon Web Services (AWS) that provides resizable and scalable compute capacity in the cloud. In simple terms, AWS EC2 allows you to launch and manage virtual machines, known as instances, in the AWS cloud.
AWS AMI
AWS AMI, or Amazon Machine Image, is a pre-configured virtual machine image used to create and launch Amazon Elastic Compute Cloud (EC2) instances
1 2 3

Javier Ruiz

IT Wonder Lab tutorials are based on the rich and diverse experience of Javier Ruiz, who founded and bootstrapped a SaaS company in the energy sector. His company, which was later acquired by a NASDAQ traded company, managed over €2 billion per year of electricity for prominent energy producers across Europe and America. Javier has more than 20 years of experience in building and managing IT companies, developing cloud infrastructure, leading cross-functional teams, and transitioning his own company from on-premises, consulting, and custom software development to a successful SaaS model that scaled globally.

4 comments on “How to programmatically use your public Internet IP address in Terraform?”

  1. Just a quick fix because the script whatismyip.sh wasn’t working for me, I don’t if its due to my distro (Ubuntu 20.04)…

    I’d only added a “-4″ at the end of the dig command:

    #!/bin/bash
    set -e
    INTERNETIP=”$(dig +short myip.opendns.com @resolver1.opendns.com -4)”
    echo $(jq -n –arg internetip “$INTERNETIP” ‘{“internet_ip”:$internetip}’)

    Now is showing my IPv4, if the IPv6 is required just change the “-4” to “-6” and you’re good to go.

    1. Thanks, Reque, you are right.

      I believe that if you have IPV6 and IPV4 addresses, then the command shows both. Your fix is needed to select the required IP version. I will add it to the tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *


linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram