Shashi Techlogues

Using Terraform Variables

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 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 note 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.

Using 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 a hardcoded IP, it’s using the value from the variable.

Conclusion

  • By using 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.

In the subsequent article, we will explore more of Terraform.

Thanks for reading. If you have some feedback, please provide your response or reach out to me on Twitter or Github.

Happy Coding!!!