SSH Access from a Dynamic IP in AWS Security Group using Terraform

Girish V P
ADIBI Technologies, Basavanagudi, Blore.
2 min readFeb 24, 2024

Allowing SSH Access from static IP address to AWS Instance is not a big challenge. What if you want to allow the SSH access from your workstation IP which keeps changing every time you reboot your wi-fi device. Let us see how we over come this with the terraform code.

1 — Create a shell script like below. This shell script returns your workstation’s dynamic ip in json format.

My_IP=`curl ifconfig.me`
echo "{ \"My_IP\": \"$My_IP/32\" }

2 — Write the terraform code for the provider.

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}

# Configure the AWS Provider
provider "aws" {
region = "us-east-1"
access_key = "Your Access Key"
secret_key = "Your Secret Key"
}

3 — Create an external data source like below. getname.sh is the shell script we created in the step 1.

data "external" "workstation_ip"{
program= ["bash", "getname.sh"]
}

4 — Create the VPC data source as we use an existing VPC for creating the new security group.

data "aws_vpc" "vpc" {
id = "Your_VPC-ID"
}

5 — Create security Group like below. Here workstation_ip is referred by external data source and My_IP by getname.sh script.

resource "aws_security_group" "public-sg-1" {
name = "Public SG"
description = "Public internet access"
vpc_id = data.aws_vpc.vpc.id

tags = {
Name = "Public SG"
Project = "Project-1"
ManagedBy = "terraform"
Programmer = " Girish V P"
}
}

resource "aws_security_group_rule" "Public_Egress_ALL" {
type = "egress"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
security_group_id = aws_security_group.public-sg-1.id
}

resource "aws_security_group_rule" "Public_Ingress_SSH" {
type = "ingress"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = [ data.external.workstation_ip.result.My_IP ]
security_group_id = aws_security_group.public-sg-1.id
}

Result

Conclusion

We are able to create terraform script which detects the dynamic IP and allow SSH access to an EC2 service.

Note: Recommended to test thoroughly before implementing in a production environment.

--

--