Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to identify the public ip of the terraform execution environment and add it to the security group

Tags:

terraform

I want to identify the public IP of the terraform execution environment and add it to aws security group inbound to prevent access from other environments.

Currently, I am manually editing the values in the variables.tf file.

variables.tf

variable public_ip_address {   default     = "xx" } 

I would like to execute the "curl ifconfig.co" command on the local host and automatically set the security group based on the result

Is there a way to do such things?

I could do it by putting the result of local-exec in some variable but I don't know how to do it.

Thank you for reading my question.

like image 314
negabaro Avatar asked Oct 16 '17 05:10

negabaro


People also ask

How do I add a security group to my EC2 instance terraform?

To enable access to the EC2 instance's web server, you must define a security group that allows ingress traffic on port 80 and all egress traffic, and associate the security group with your instance. Open the AWS Provider documentation page. Search for security_group and select the aws_security_group resource.


1 Answers

There's an easier way to do that without any scripts. The trick is having a website such as icanhazip.com which retrieve your IP, so set it in your terraform file as data:

data "http" "myip" {   url = "http://ipv4.icanhazip.com" } 

And whenever you want to place your IP just use data.http.myip.body, example:

ingress {   from_port = 5432   to_port = 5432   protocol = "tcp"   cidr_blocks = ["${chomp(data.http.myip.body)}/32"] } 
  • Note I used terraform chomp() method to remove any trailing space or new line which comes with body.

  • You can use your ipv6 with http://ipv6.icanhazip.com. Take care by just using http://icanhazip.com because it can retrieve ipv4 or ipv6

like image 71
Wagner Leonardi Avatar answered Oct 01 '22 20:10

Wagner Leonardi