Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Terraform Cookbook

You're reading from   Terraform Cookbook Master Infrastructure as Code efficiency with real-world Azure automation using Terraform

Arrow left icon
Product type Paperback
Published in Aug 2023
Publisher Packt
ISBN-13 9781804616420
Length 634 pages
Edition 2nd Edition
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Mikael Krief Mikael Krief
Author Profile Icon Mikael Krief
Mikael Krief
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Setting Up the Terraform Environment 2. Writing Terraform Configurations FREE CHAPTER 3. Scaling Your Infrastructure with Terraform 4. Using Terraform with External Data 5. Managing Terraform State 6. Applying a Basic Terraform Workflow 7. Sharing Terraform Configuration with Modules 8. Provisioning Azure Infrastructure with Terraform 9. Getting Starting to Provisioning AWS and GCP Infrastructure Using Terraform 10. Using Terraform for Docker and Kubernetes Deployment 11. Running Test and Compliance Security on Terraform Configuration 12. Deep-Diving into Terraform 13. Automating Terraform Execution in a CI/CD Pipeline 14. Using Terraform Cloud to Improve Team Collaboration 15. Troubleshooting Terraform Errors 16. Other Books You May Enjoy
17. Index
Appendix A: Terraform Cheat Sheet 1. Appendix B: Terraform Resources

Manipulating variables

When you write a Terraform configuration where all the properties are hardcoded in the code, you often find yourself faced with the problem of having to duplicate it to reuse it.

In this recipe, we’ll learn how to make the Terraform configuration more dynamic by using variables.

Getting ready

To begin, we are going to work on the main.tf file, which contains a basic Terraform configuration:

resource "azurerm_resource_group" "rg" {
  name     = "My-RG"
  location = "West Europe"
}

As we can see, the name and location properties have values statically written in the code.

Let’s learn how to make them dynamic using variables.

The source code of this recipe is available at https://github.com/PacktPublishing/Terraform-Cookbook-Second-Edition/tree/main/CHAP02/variables.

How to do it…

Perform the following steps:

  1. In the same main.tf file, add the following variable declarations:
    variable "resource_group_name" {
      description ="The name of the resource group"
    }
    variable "location" {
      description ="The name of the Azure region"
      default ="westeurope"
    }
    
  2. Then, modify the Terraform configuration we had at the beginning of this recipe so that it refers to our new variables, as follows:
    resource "azurerm_resource_group" "rg" {
      name     = var.resource_group_name
      location = var.location
    }
    
  3. Finally, in the same folder that contains the main.tf file, create a new file called terraform.tfvars and add the following content:
    resource_group_name = "My-RG"
    location            = "westeurope"
    

How it works…

In Step 1, we wrote the declaration of the two variables, which consists of the following elements:

  • A variable name: This must be unique to this Terraform configuration and must be explicit enough to be understood by all the contributors of the code.
  • A description of what this variable represents: This description is optional but is recommended because it can be displayed by the CLI and can also be integrated into the documentation, which is automatically generated.
  • A default value: This is optional. Not setting a default value makes it mandatory to enter a value.

Then, in Step 2, we modified the Terraform configuration to use these two variables. We did this using the var.<name of the variable> syntax.

Finally, in Step 3, we set values for the variables in the terraform.tfvars file, which is used natively by Terraform.

The result of executing this Terraform configuration is shown in the following screenshot:

Une image contenant texte  Description générée automatiquement

Figure 2.6: Using the terraform.tfvars file

There’s more…

Setting a value for the variable is optional in the terraform.tfvars file since we have set a default value for the variable.

Apart from this terraform.tfvars file, it is possible to give a variable a value using the -var option of the terraform plan and terraform apply commands, as shown in the following command:

terraform plan -var "location=westus"

So, with this command, the location variable declared in our code will have a value of westus instead of westeurope.

In addition, in the 0.13 version of Terraform, we can now create custom validation rules for variables, which makes it possible for us to verify a value during the terraform plan execution.

In our recipe, we can complete the location variable with a validation rule in the validation block as shown in the following code:

variable "location" {
  description ="The name of the Azure location"
  default ="westeurope"
  validation {
    condition = contains(["westeurope","westus"], var.location)          error_message = "The location must be westeurope or westus."
  }
}

In the preceding configuration, the rule checks if the value of the location variable is westeurope or westus.

If you put in an invalid value for the location variable, such as francecentrale, the validation rule will display The location must be westeurope or westus:

Une image contenant texte  Description générée automatiquement

Figure 2.7: Variable validation

For more information about variable custom rules validation, read the documentation at https://www.terraform.io/docs/configuration/variables.html#custom-validation-rules.

Finally, there is another alternative to setting a value to a variable, which consists of setting an environment variable called TF_VAR_<variable name>. In our case, we can create an environment variable called TF_VAR_location with a value of westus and then execute the terraform plan command in the classical way.

Note that using the -var option or the TF_VAR_<name of the variable> environment variable doesn’t hardcode these variables’ values inside the Terraform configuration. Terraform makes it possible for us to give values of variables on the fly. But be careful – these options can have consequences if the same code is executed with other values initially provided in parameters and if the plan’s output isn’t reviewed carefully.

See also

In this recipe, we looked at the basic use of variables. We will learn how to protect sensitive variables in the next recipe, and we will examine more advanced uses of these variables when we learn how to manage environments in Chapter 3, Scaling Your Infrastructure with Terraform, in the Managing infrastructure in multiple environments recipe.

For more information on Terraform variables, refer to the documentation at https://www.terraform.io/docs/configuration/variables.html.

You have been reading a chapter from
Terraform Cookbook - Second Edition
Published in: Aug 2023
Publisher: Packt
ISBN-13: 9781804616420
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image