Skip to content

Blog rovingdev

Go back

How to share constant values in Terraform?

Edit page

This tutorial will help you to solve the problem where you want to share common values among TF files or across modules.

Before approaching the problem, let’s get some overview of Terraform and IaC. Default alt text


Terraform and IaC:


Problem:

Let’s come back to the problem statement, the agenda of this tutorial is to share common values among TF files.

Why it is little complicated to do it in terraform?

Terraform’s modular design and lack of a built-in constant management system make it challenging to share constants across multiple modules and configurations.

Solution:

There are many ways to share common variables/constants/values, but I am going to focus on a method where we are going to create a separate module.

Let’s assume this is the structure of your current terraform infra code directory:

Terminal window
.
├── instances.tf
├── outputs.tf
├── terraform.tfvars
├── variables.tf
└── version.tf

Shareable/common value can be added this way:

  1. Add a module by creating a directory with the name of your choice, here I am common_shared_vars as directory name.
  2. Under that, I will create output.tf
  3. I will mention the variable this way in the output.tf file
output "vm_prefix" {
value = "sample-tf-vm"
}
  1. Import the module by creating tf file, I am naming it as same as module directory for simplicity, common_shared_vars.tf .
  2. In the common_shared_vars.tf file, source common_shared_vars directory. Like this:
module "common_shared_vars"{
source = "./common_shared_vars"
}
  1. After this, all output values from common_shared_vars/output.tf file can be used like:
Terminal window
${module.common_shared_vars.vm_prefix}
  1. Usage example, here I want to use vm_prefix in name of the vm resource.
resource "aws_instance" "my_instance" {
ami = "ami-abcdxyz" # Update with a valid AMI ID
instance_type = "t2.micro"
tags = {
Name = "${module.common_shared_vars.vm_prefix}_${var.vm_name}"
}
}
  1. Infrastructure code directory will look something like this:
Terminal window
.
├── common_shared_vars
└── output.tf
├── common_shared_vars.tf
├── instances.tf
├── outputs.tf
├── terraform.tfvars
├── variables.tf
└── version.tf
  1. This is not the only way to solve the common shareable value/constant, there are other ways too. But, I prefer this one.

All codes related to this tutorial on my GitHub. Click here for Github link of this tutorial.


Edit page
Share this post on:

Previous Post
Unlocking Docker: A Beginner's Guide to Ubuntu and Node.js installation
Next Post
What could be the future of Stack Overflow community after OpenAI partnership?