DEV Community

Discussion on: [Terraform] Deploy EC2 Instance in Minutes

Collapse
 
tadeubernacchi profile image
Tadeu Bernacchi

How do I set in the security group section my public_ip? Like curl ifconfig.me?
I just want to allow SSH from my IP.
Do you have any idea how can I accomplished that?

Collapse
 
hi_artem profile image
Artem

In you aws_security_group resource, you can specify allowed IPs using cidr_block. For example:

resource "aws_security_group" "ubuntu" {
  name        = "ubuntu-security-group"
  description = "Allow SSH only for 1.1.1.1"

  ingress {
    description = "SSH"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["1.1.1.1/32"]
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tadeubernacchi profile image
Tadeu Bernacchi • Edited

I was thinking in somehow my .tf files execute and save the value of a command to accomplish that, I'd to replace the ["1.1.1.1/32"] to 'curl ifconfig.me'.

Thread Thread
 
hi_artem profile image
Artem • Edited

i see. i have not tested it, but theoretically you can do something like that:

  1. create a bash script to get ip:
#!/usr/bin/env bash
echo '{"result":"'$(curl ifconfig.me)'"}'
Enter fullscreen mode Exit fullscreen mode
  1. use the script as data source in tf file:
data "external" "script" {
  program = ["bash", "./get_ip.sh"] // get_ip.sh is your script name
}

resource "aws_security_group" "ubuntu" {
  name        = "ubuntu-security-group"
  description = "Allow SSH only for 1.1.1.1"

  ingress {
    description = "SSH"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["${data.external.script.result}/32"]
  }
}

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
tadeubernacchi profile image
Tadeu Bernacchi

WOW - That's nice, I'm going try it! Thank you!!!