Terraform(IAAC)- Variables

n00🔑
2 min readDec 2, 2023

Example- Using a variable for specifying the same “IP address” in different ingress rules.

variables.tf

resource "aws_security_group" "var_demo" {
name = "apni-variables"

ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [var.vpn_ip]
}

ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = [var.vpn_ip]
}

ingress {
from_port = 53
to_port = 53
protocol = "tcp"
cidr_blocks = [var.vpn_ip]
}
}

var-example.tf

variable "vpn_ip" {
default = "111.50.30.40/32"
}

Here’s a breakdown of what each part does:

  1. variable "vpn_ip": This block in the variables.tf file defines a variable named vpn_ip with a default value of "111.50.30.40/32". Variables in Terraform are a way to define values that can be reused throughout your Terraform code.

2.resource "aws_security_group" "var_demo": This block in the var-example.tf file is used to create a security group named apni-variables. It specifies that inbound traffic on ports 443, 80, and 53 (which are typically used for HTTPS, HTTP, and DNS traffic respectively) is allowed from the IP address specified by the vpn_ip variable.

3. The line cidr_blocks = [var.vpn_ip] is an example of how to use variables in Terraform. Here, var.vpn_ip is used to reference the value of the vpn_ip variable. This allows you to change the IP address in…

--

--