How to write basic code for Terraform

IaC
スポンサーリンク
スポンサーリンク

At first

Terraform is an IaC (Infrastructure as Code) tool that builds resources such as virtual networks and virtual computers in the cloud with code.

If you build an infrastructure on the cloud with Terraform, you can manage it with code, so you can manage history etc. using a code management tool such as git like a general program.

Please note that the code described on this page is valid for Terraform 0.14.4 at the time of writing. Older versions, such as 0.11 or earlier, may be written differently.

Please refer to the link below for how to install and run Terraform.

Main files in Terraform

tf file

The Terraform code will be coded into the tf file.

You can place only one tf file in the working directory for running Terraform, or you can divide it into multiple files.

You can name the tf file freely, but there are many naming patterns as shown below.

File nameRole
main.tfA tf file for defining resources to be built on the cloud.
variables.tfA tf file for defining variables used by Terraform.
outputs.tfA tf file for defining variables output by running Terraform.
[service name].tfA tf file for defining resources for each service by adding the name of the cloud service (network, instance, etc.) to the file name.

tfvars file

This file is used to define the values ​​of variables that you want to load when Terraform is executed.

If the file name is “terraform.tfvars”, the value of the variable set in the tfvars file can be automatically read when Terraform is executed.

If you want to rename the file, you need to specify -var-file [filename] .tfvars as a parameter when running Terraform.

The tfvars file is used to set confidential information such as API keys and passwords for accessing the cloud without being subject to code management by git. By doing this, you can prevent confidential information from being posted on git.

tfstate file

The tfstate file is a JSON-formatted file created when terraform apply is executed. By default, it is created in the directory where terraform apply is executed with the file name “terraform.tfstate”.

Terraform manages the current state of resources built on the cloud using tfstate files to determine which resources should be added / removed / changed on the cloud from the state of the tf file and terraform.tfstate.

Since the tfstate file is an important file, it is often saved in Object Storage on the cloud when it is used in actual business.

Syntax

Comments

Single-line comments start with #.

# Single-line Comment

Enclose multi-line comments in / * * /.

/* 
Multi-line Comment
Multi-line Comment
*/

Number

Numbers are written in decimal numbers as they are. If 0x is added, it will be treated as a hexadecimal number.

value = 1
value = 0x1

String

Enclose the string in "".

value = "String"

Bool value

The bool value can be true or false.

value = true
value = false

Array

Enclose the array in [] and separate the values ​​with ,.

value = [ "a", "b", "c", "d" ]

Map

Enclose the array with {} and separate the key and the value with : and ,.

value = { "key1" : "value1", "key2" : "value2", "key3" : "value3" }

Calculation operator

You can use +(addition),-(subtraction), *(multiplication), /(division), and % (remainder) for numbers.

value = a + b
value = a - b
value = a * b
value = a / b
value = a % b

Equivalence operators

It is possible to use ==(match), !=(mismatch) and return a bool value as the result value.

value = a == b
value = a != b

Comparison operator

You can use <, <=, >, >= for numbers and return a bool value as the result.

value = a < b
value = a  <= b="" value="a">b
value = a >= b</=>

Logical operators

You can use ||(logical sum), &&(logical product), and !(Negation) for the bool value, and return the bool value as the result value.

value = a || B
value = a && b
value = !a

Conditional expression

The conditional expression is specified by ? And returns either of the two values ​​depending on the judgment result.

value = (a == b) ? a : b

In the above case, if a and b are equal, then a is returned, otherwise b is returned.

Variable

In Terraform, you can declare three types of variables, input variables, output variables, and local variables, depending on the role.

Input variable

A variable that can receive values ​​from outside the tf file, such as a split tf file or tfvars file.

Declare the variable as follows and name the variable in the variable_name part.

variable "variable_name" {
}

The following settings can be made as options when declaring variables.

  • default: The default value of the variable
    type: A type that can be accepted in a variable (number, string, bool, etc.)
    description: Variable description
    validation: A rule for validating the value of a variable
    sensitive: If set to true, the value of the variable will not be displayed on the screen when Terraform is executed.
variable "string_variable_name" {
  type = string
  description = "String variable description"
  default = "default value"
}

variable "list_variable_name" {
  type = list(number)
  description = "List variable description"
  default = [ 0, 1, 2, 3 ]
}

To use an input variable in a tf file, use var followed by the variable name.

value = var.variable_name

Local variables

Local variables are variables that can only be used in tf files.

Declare the variable as follows and name the variable in the local_variable_name part.

locals {
  local_variable_name = "local variable"
}

You can also declare multiple local variables at the same time as shown below.

locals {
  local_variable_name1 = "local variable1"
  local_variable_name2 = "local variable2"
}

To use a local variable in a tf file, use local followed by the variable name.

value = local.local_variable_name

Output variable

Output variables are variables that can be used when outputting values ​​to the console screen or when outputting values ​​from a module (a group of resources located in a location other than the work directory).

Declare the variable as follows and name the variable in the output_name part.

output "output_name" {
}

The following settings can be made as options when declaring variables.

  • description: Description of variables displayed on the screen at output
    sensitive: If set to true, the value of the variable will not be displayed on the screen when Terraform is executed.
    depends_on: Definition of dependencies
variable "string_output_name" {
  description = "Output variable description"
}

To use an output variable in a tf file, use module followed by the module’s local name and variable name.

value = module.local_name.variable_name

Provider

Terraform can connect to multiple cloud services such as AWS and Azure depending on the provider.

Define it in the provider block as shown below, and specify the name of the provider such as aws in provider_name.

provider "provider_name" {
}

For how to define each provider, search for the cloud service you want to connect to from here and click it to display the screen below. Click “documentation” to check.

Datasource

The data source is for retrieving externally defined data so that it can be used without a tf file.

Define it in the data block as shown below, specify the name of the data source you want to acquire in data_source_name, the local name used in the tf file in local_name, and the search conditions you want to retrieve in the attribute in the block. ..

data "data_source_name" "local_name" {
}

To use a data source in a tf file, use data followed by the data source name, local name, and the attribute you want to get.

value = data.data_source_name.local_name.attribute_name

Resource

Resources are for defining things to build on the cloud, such as virtual networks and virtual computers.

Define in the resource block as shown below, specify the name of the resource to be built in resource_name, specify the local name of the resource to be used in the tf file in local_name, and the parameter of the resource to be built in the attribute in the block. Is specified.

resource "resource_name" "local_name" {
}

The following can be specified in the resource block.

  • depends_on: Resource and module dependency settings
    count: Create the specified number of resources
    for_each: Create resources for the number of map elements (map values ​​can be set for resources)
    provider: Set the provider to use when there are multiple providers
    lifecycle: Settings when a resource change occurs

To use a resource in a tf file, specify the resource name, local name, and the attribute you want to get.

value = resource_name.local_name.attribute_name

Module

A module is a tf file that can be used in common from multiple working directories by placing it in a directory different from the working directory.

Define in the module block as shown below, specify the local name of the module to be used in the tf file in local_name, and set the value in the input variable defined in the module in the block.

module "local_name" {
}

The following can be specified in the module block.

  • depends_on: Resource and module dependency settings
    count: Create the specified number of modules
    for_each: Create modules for the number of map elements (map values ​​can be set in modules)
    provider: Set the provider to use when there are multiple providers

The way to use the module in the tf file is to use the output variable.

value = module.local_name.variable_name

At the end of the day

That’s all for writing the basic code of Terraform.

Please try it because the environment is built using Terrform to the free frame of OCI (Oracle Cloud Infrastructure) at the following URL.

The code is also available on github.

Comment

スポンサーリンク