官术网_书友最值得收藏!

  • Learning DevOps
  • Mikael Krief
  • 321字
  • 2021-06-24 12:32:06

Dynamizing the code with variables and interpolation functions

When writing Terraform code, it is important to take into account from the beginning that the infrastructure that will host an application is very often the same for all stages, but only some information will vary from one stage to another, such as the name of the resources and the number of instances.

To give more flexibility to the code, we must use variables in the code with the following steps: 

  1. Declare the variables by adding the following sample code in the global Terraform code, or we can add it in another file (such as variables.tf) for better readability of the code:
variable "resource_group_name" {
description ="Name of the resource group"
}

variable "location" {
description ="Location of the resource"
default ="West Europe"
}

variable "application_name" {
description ="Name of the application"
}
  1. Instantiate their values in another file, .tfvars, named terraform.tfvars with the syntax, variable_name=value, like the following:
resource_group_name ="bookRg"
application_name ="book"
  1. Use these variables in code with var.<name of the variable>; for example, in the resource group Terraform code, we can write the following:
resource "azurerm_resource_group" "rg" {
name = var.resoure_group_name
location = var.location
tags {
environment = "Terraform Azure"
}
}

In addition, Terraform has a large list of built-in functions that can be used to manipulate data or variables. To learn more about these functions, consult the documentation here: https://www.terraform.io/docs/configuration/functions.html.

Of course, there are many other good practices, but these are to be applied from the first lines of code to make sure that your code is well maintained.

The complete final code of this sample is available here:  https://github.com/PacktPublishing/Learning_DevOps/tree/master/CHAP02/03-terraform_vars_interp.

We have written a Terraform script, with best practices, which allows us to create a simple cloud infrastructure in Azure that provides a network and a virtual machine. Let's now look at how to run Terraform with our code for provisioning this infrastructure.

主站蜘蛛池模板: 利津县| 商都县| 瑞丽市| 厦门市| 利津县| 通许县| 平顶山市| 长岛县| 马关县| 玛多县| 桑日县| 册亨县| 临颍县| 南开区| 宜兴市| 汤阴县| 密云县| 康马县| 榆中县| 临夏县| 濮阳县| 左贡县| 阳原县| 右玉县| 江西省| 祥云县| 福海县| 武川县| 江都市| 迭部县| 衡山县| 溆浦县| 永靖县| 郯城县| 湘阴县| 浦城县| 五河县| 闽侯县| 乐陵市| 西藏| 突泉县|