Introduction
Terraform variables are a central source from which values can be imported. In this way terraform variables are helpful in creating and managing centrally controlled reusable values.
Let’s see how we can use the terraform variables to write clean code and avoid repetition using reusability.
We are creating an AWS security group to demonstrate the variable's usage.
resource "aws_security_group" "sg" {
name = "demo-security-group"ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["116.30.45.50/32"]
}ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["116.30.45.50/32"]
}ingress {
from_port = 53
to_port = 53
protocol = "tcp"
cidr_blocks = ["116.30.45.50/32"]
}
}
Take a not at cidr_blocks we are repeating the value “116.30.45.50/32” 3 times.
There are a couple of problems here.
- We are violating the DRY principle.
- Tomorrow if we want to change the value we need to update it in three places, we might forget to change it at some places in the real production codebase where we might have 20–25 repetitions.
- The code is not clean.
To address these problems we can use Terraform Variables.
Let’s create another file variables.tf with the following content.
variable "vpn_id" {
default = "116.30.45.50/32"
}
We have created a variable called vpn_id and provided the default value.
Now we can change our security_group resource group code to use this variable.
resource "aws_security_group" "sg" {
name = "demo-security-group"ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [var.vpn_id]
}ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = [var.vpn_id]
}ingress {
from_port = 53
to_port = 53
protocol = "tcp"
cidr_blocks = [var.vpn_id]
}
}
As you can see now instead of hardcoded IP it’s using the value from the variable.
Conclusion
- By using the variables we have avoided static repetition.
- The code is now much cleaner and adheres to the DRY principle.
- Changing the CIDR value is much easier now, thus increasing code maintainability.
Comments
Post a Comment