Terraform map variable

Terraform map variable DEFAULT

» Input Variables

Input variables serve as parameters for a Terraform module.

When used in the root module of a configuration, variables can be set from CLI arguments and environment variables. For child modules, they allow values to pass from parent to child.

This page assumes you're familiar with the configuration syntax already.

» Example

Input variables can be defined as follows:

» Description

The block configures a single input variable for a Terraform module. Each block declares a single variable.

The name given in the block header is used to assign a value to the variable via the CLI and to reference the variable elsewhere in the configuration.

Within the block body (between ) is configuration for the variable, which accepts the following arguments:

  • (Optional) - If set this defines the type of the variable. Valid values are , , and . If this field is omitted, the variable type will be inferred based on . If no is provided, the type is assumed to be .

  • (Optional) - This sets a default value for the variable. If no default is provided, Terraform will raise an error if a value is not provided by the caller. The default value can be of any of the supported data types, as described below. If is also set, the given value must be of the specified type.

  • (Optional) - A human-friendly description for the variable. This is primarily for documentation for users using your Terraform configuration. When a module is published in Terraform Registry, the given description is shown as part of the documentation.

The name of a variable can be any valid identifier. However, due to the interpretation of module configuration blocks, the names , and are reserved for Terraform's own use and are thus not recommended for any module intended to be used as a child module.

The default value of an input variable must be a literal value, containing no interpolation expressions. To assign a name to an expression so that it may be re-used within a module, use Local Values instead.

» Strings

String values are simple and represent a basic key to value mapping where the key is the variable name. An example is:

A multi-line string value can be provided using heredoc syntax.

Terraform performs automatic conversion from string values to numeric and boolean values based on context, so in practice string variables may be used to set arguments of any primitive type. For boolean values in particular there are some caveats, described under Booleans below.

» Maps

A map value is a lookup table from string keys to string values. This is useful for selecting a value based on some other provided value.

A common use of maps is to create a table of machine images per region, as follows:

» Lists

A list value is an ordered sequence of strings indexed by integers starting with zero. For example:

» Booleans

Although Terraform can automatically convert between boolean and string values, there are some subtle implications of these conversions that should be completely understood when using boolean values with input variables.

It is recommended for now to specify boolean values for variables as the strings and , to avoid some caveats in the conversion process. A future version of Terraform will properly support boolean values and so relying on the current behavior could result in backwards-incompatibilities at that time.

For a configuration such as the following:

The false is converted to a string when running Terraform.

Then, depending on where you specify overrides, the behavior can differ:

  • Variables with boolean values in a file will likewise be converted to "0" and "1" values.

  • Variables specified via the command line flag will be literal strings "true" and "false", so care should be taken to explicitly use "0" or "1".

  • Variables specified with the environment variables will be literal string values, just like .

A future version of Terraform will fully support first-class boolean types which will make the behavior of booleans consistent as you would expect. This may break some of the above behavior.

When passing boolean-like variables as parameters to resource configurations that expect boolean values, they are converted consistently:

  • "1" and "true" become
  • "0" and "false" become

The behavior of conversion in this direction (string to boolean) will not change in future Terraform versions. Therefore, using these string values rather than literal booleans is recommended when using input variables.

» Environment Variables

Environment variables can be used to set the value of an input variable in the root module. The name of the environment variable must be followed by the variable name, and the value is the value of the variable.

For example, given the configuration below:

The variable can be set via an environment variable:

Maps and lists can be specified using environment variables as well using HCL syntax in the value.

For a list variable like so:

The variable could be set like so:

Similarly, for a map declared like:

The value can be set like this:

» Variable Files

Values for the input variables of a root module can be gathered in variable definition files and passed together using the option.

For all files which match or present in the current directory, Terraform automatically loads them to populate variables. If the file is located somewhere else, you can pass the path to the file using the flag. It is recommended to name such files with names ending in .

Variables files use HCL or JSON syntax to define variable values. Strings, lists or maps may be set in the same manner as the default value in a block in Terraform configuration. For example:

The flag can be used multiple times per command invocation:

Note: Variable files are evaluated in the order in which they are specified on the command line. If a particular variable is defined in more than one variable file, the last value specified is effective.

» Variable Merging

When multiple values are provided for the same input variable, map values are merged while all other values are overridden by the last definition.

For example, if you define a variable twice on the command line:

Then the value of will be , since it was the last definition seen.

However, for maps, the values are merged:

The resulting value of will be:

There is no way currently to unset map values in Terraform. Whenever a map is modified either via variable input or being passed into a module, the values are always merged.

» Variable Precedence

Both these files have the variable defined:

foo.tfvars

bar.tfvars

When they are passed in the following order:

The result will be that will contain the value because has the last definition loaded.

Definition files passed using the flag will always be evaluated after those in the working directory.

Values passed within definition files or with will take precedence over environment variables, as environment variables are considered defaults.

Sours: https://www.terraform.io/docs/configuration-0-11/variables.html

Spread the Knowledge

Terraform variable Map Type Explained!!!

Maps are a collection of string keys and string values. These can be useful for selecting values based on predefined parameters such as the server configuration by the monthly price.

We’ve replaced our sensitive strings with variables, but we still are hard-coding AMIs. Unfortunately, AMIs are specific to the region that is in use. One option is to just ask the user to input the proper AMI for the region, but Terraform can do better than that with maps.

dynamic lookup – The square-bracket index notation used here is an example of how the map type expression is accessed as a variable, with [var.region] referencing the var.amis declaration for dynamic lookup.

static value lookup – the map type expression can also use a static value lookup directly with var.amis[“us-east-1”].

Maps are a way to create variables that are lookup tables. An example will show this best. Let’s extract our AMIs into a map and add support for the us-west-2 region as well:

Rajesh Kumar

Rajesh Kumar

Mentor for DevOps - DevSecOps - SRE - Cloud - Container & Micorservices at Cotocus

Website - www.RajeshKumar.xyz

I can help in the following:
- DevOps - DevSecOps - SRE
- Continuous Integration & Delivery
- Continuous Deployment & Inspection
- Technical Debt Reduction
- Containerization/Micro Services Using Kubernetes & Docker
- Cloud Migration using AWS-Azure-GoogleCloud
- Enterprise observability

Rajesh Kumar

Latest posts by Rajesh Kumar (see all)

ExplainedMapTerraformTutorialVariable

Sours: https://www.devopsschool.com/blog/terraform-variable-map-type-explained/
  1. 192kg to pounds
  2. Morimoto hid h1
  3. Pac man world walkthrough
  4. P touch design and print

Define Input Variables

You now have enough Terraform knowledge to create useful configurations, but the examples so far have used hard-coded values. Terraform configurations can include variables to make your configuration more dynamic and flexible.

»Prerequisites

After following the other tutorials in this collection, you will have a directory named with the following configuration in a file called .

terraform{required_providers{aws={source="hashicorp/aws"version="~> 3.27"}}required_version=">= 0.14.9"}provider "aws" {profile="default"region="us-west-2"}resource "aws_instance""app_server"{ami="ami-08d70e59c07c61a3a"instance_type="t2.micro"tags={Name="ExampleAppServerInstance"}}

Ensure that your configuration matches this, and that you have run in the directory.

»Set the instance name with a variable

The current configuration includes a number of hard-coded values. Terraform variables allow you to write configuration that is flexible and easier to re-use.

Add a variable to define the instance name.

Create a new file called with a block defining a new variable.

variable "instance_name" {description="Value of the Name tag for the EC2 instance"type= string default="ExampleAppServerInstance"}

Note: Terraform loads all files in the current directory ending in , so you can name your configuration files however you choose.

In , update the resource block to use the new variable. The variable block will default to its default value ("ExampleAppServerInstance") unless you declare a different value.

resource "aws_instance" "app_server" { ami = "ami-08d70e59c07c61a3a" instance_type = "t2.micro" tags = {- Name = "ExampleAppServerInstance"+ Name = var.instance_name }}

»Apply your configuration

Apply the configuration. Respond to the confirmation prompt with a .

$terraform applyAn execution plan has been generated and is shown below.Resource actions are indicated with the following symbols: + createTerraform will perform the following actions:#aws_instance.app_server will be created + resource "aws_instance" "app_server" { + ami = "ami-08d70e59c07c61a3a" + arn = (known after apply)##...Plan: 1 to add, 0 to change, 0 to destroy.Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yesaws_instance.app_server: Creating...aws_instance.app_server: Still creating... [10s elapsed]aws_instance.app_server: Still creating... [20s elapsed]aws_instance.app_server: Still creating... [30s elapsed]aws_instance.app_server: Still creating... [40s elapsed]aws_instance.app_server: Creation complete after 50s [id=i-0bf954919ed765de1]Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Now apply the configuration again, this time overriding the default instance name by passing in a variable using the flag. Terraform will update the instance's tag with the new name. Respond to the confirmation prompt with .

$terraform apply -var "instance_name=YetAnotherName"aws_instance.app_server: Refreshing state... [id=i-0bf954919ed765de1]An execution plan has been generated and is shown below.Resource actions are indicated with the following symbols: ~ update in-placeTerraform will perform the following actions:#aws_instance.app_server will be updated in-place ~ resource "aws_instance" "app_server" { id = "i-0bf954919ed765de1" ~ tags = { ~ "Name" = "ExampleAppServerInstance" -> "YetAnotherName" }#(26 unchanged attributes hidden)#(4 unchanged blocks hidden) }Plan: 0 to add, 1 to change, 0 to destroy.Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yesaws_instance.app_server: Modifying... [id=i-0bf954919ed765de1]aws_instance.app_server: Modifications complete after 7s [id=i-0bf954919ed765de1]Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Setting variables via the command-line will not save their values. Terraform supports many ways to use and set variables so you can avoid having to enter them repeatedly as you execute commands. To learn more, follow our in-depth tutorial, Customize Terraform Configuration with Variables.

Sours: https://learn.hashicorp.com/tutorials/terraform/aws-variables
Input Variables in Terraform - Terraform Tutorial - #7

Variable keys in terraform maps

The accepted answer describes how to do dynamic lookups in an existing map. For constructing maps with dynamic keys, in HCL2 (0.12), you can use a quoted interpolation expression in the key:

And once issue #21566 is fixed, you can replace with , which is the method described in the documentation.

(The same caveat as below applies here as well: if contains one of those literal keys as its value, then it will replace it.)

The accepted answer describes how to do dynamic lookups in an existing map. For constructing maps with dynamic keys, in HCL2 (0.12), you have two ways:

For expressions +

You can use for expressions to dynamically build a map from one or more variables for your keys, and then use that in combination with the function to build a new map with a mix of static and dynamic keys:

Alternatively, you can use to construct it in one shot:

You can then use this map in a resource:

One caveat is that if is equal to either or , then it'll overwrite your static value. You can avoid this by swapping the arguments in or reordering the lists in , though such a collision would more likely be a configuration error that should be caught & fixed before applying.

Sours: https://stackoverflow.com/questions/35491987/variable-keys-in-terraform-maps

Map variable terraform

devops-school/terraform-map-variable.tf

Example 1===============================Maps are a way to create variables that are lookup tables.An example will show this best.Let's extract our AMIs into a map and add support for the us-west-2 region as well:variable"amis" { type ="map" default = {"us-east-1"="ami-b374d5a5""us-west-2"="ami-4b32be2b" }}A variable can have a map type assigned explicitly, or it can be implicitly declared as a map by specifying a default value that is a map.The above demonstrates both.Then, replace the aws_instance with the following:resource"aws_instance""example" { ami =var.amis[var.region] instance_type ="t2.micro"}Example 2===============================variable"plans" { type ="map" default = {"5USD"="1xCPU-1GB""10USD"="1xCPU-2GB""20USD"="2xCPU-4GB" }}plan= "${var.plans["5USD"]}"The values matching to their keys can also be used to look up information in other maps.For example, underneath is a short list of plans and their corresponding storage sizes.variable"storage_sizes" { type ="map" default = {"1xCPU-1GB"="25""1xCPU-2GB"="50""2xCPU-4GB"="80" }}These can then be used to find the right storage size based on the monthly price as defined in the previous example.size = "${lookup(var.storage_sizes, var.plans["5USD"])}"variable"set_password" { default =false}Example 3===============================# Use Case of for_eachvariable"account_name" { type ="map" default = {"account1"="devops1""account2"="devops2""account3"="devops3"}}resource"aws_iam_user""iamuser" { for_each =var.account_name name ="${each.value}-iam"}
Sours: https://gist.github.com/devops-school/1f3efed15d390748b208a109f9765e0c
Terraform with AWS - Terraform lookup \u0026 map datatypes

Variable Configuration

Variables define the parameterization of Terraform configurations. Variables can be overridden via the CLI. Variable usage is covered in more detail in the getting started guide. This page covers configuration syntax for variables.

This page assumes you’re familiar with the configuration syntax already.

Example

A variable configuration looks like the following:

Description

The block configures a single input variable for a Terraform configuration. Multiple variables blocks can be used to add multiple variables.

The given to the variable block is the name used to set the variable via the CLI as well as reference the variable throughout the Terraform configuration.

Within the block (the ) is configuration for the variable. These are the parameters that can be set:

  • (optional) - If set this defines the type of the variable. Valid values are , , and . If this field is omitted, the variable type will be inferred based on the . If no is provided, the type is assumed to be .

  • (optional) - This sets a default value for the variable. If no default is provided, the variable is considered required and Terraform will error if it is not set. The default value can be any of the data types Terraform supports. This is covered in more detail below.

  • (optional) - A human-friendly description for the variable. This is primarily for documentation for users using your Terraform configuration. A future version of Terraform will expose these descriptions as part of some Terraform CLI command.


Note: Default values can be strings, lists, or maps. If a default is specified, it must match the declared type of the variable.

String values are simple and represent a basic key to value mapping where the key is the variable name. An example is:

A map allows a key to contain a lookup table. This is useful for some values that change depending on some external pivot. A common use case for this is mapping cloud images to regions. An example:

A list can also be useful to store certain variables. For example:

The usage of maps, lists, strings, etc. is documented fully in the interpolation syntax page.

Syntax

The full syntax is:

where is:

Environment Variables

Environment variables can be used to set the value of a variable. The key of the environment variable must be and the value is the value of the variable.

For example, given the configuration below:

The variable can be set via an environment variable:

Maps and lists can be specified using environment variables as well using HCL syntax in the value.

For a list variable like so:

The variable could be set like so:

Similarly, for a map declared like:

The value can be set like this:

Variable Files

Variables can be collected in files and passed all at once using the flag.

If a file named is present in the current directory, Terraform automatically loads it to populate variables. If the file is named something else, you can pass the path to the file using the flag.

Variables files use HCL or JSON to define variable values. Strings, lists or maps may be set in the same manner as the default value in a block in Terraform configuration. For example:

The flag can be used multiple times per command invocation:

Note: Variable files are evaluated in the order in which they are specified on the command line. If a variable is defined in more than one variables file, the last value specified is effective.

Precedence example:

Both these files have the variable defined:

foo.tfvars

bar.tfvars

When they are passed in the following order:

The result will be that will contain the value because has the last definition loaded.


See the source of this document at Terraform.io

Sours: https://www.koding.com/docs/terraform/configuration/variables.html/

Now discussing:

Customize Terraform Configuration with Variables

Input variables make your Terraform configuration more flexible by defining values that your end users can assign to customize the configuration. They provide a consistent interface to change how a given configuration behaves.

Unlike variables found in programming languages, Terraform's input variables don't change values during a Terraform run such as plan, apply, or destroy. Instead, they allow users to more safely customize their infrastructure by assigning different values to the variables before execution begins, rather than editing configuration files manually.

In this tutorial, you will use Terraform to deploy a web application on AWS. The supporting infrastructure includes a VPC, load balancer, and EC2 instances. You will parameterize this configuration with Terraform input variables. Finally, you will interpolate variables into strings, use variables with functions, and use variable validation.

Architecture diagram: A VPC, subnets, load balancer, and EC2 instances on AWS

»Prerequisites

In order to follow this tutorial, you will need the following:

Note: Some of the infrastructure in this tutorial may not qualify for the AWS free tier. Destroy the infrastructure at the end of the guide to avoid unnecessary charges. We are not responsible for any charges that you incur.

»Create infrastructure

Clone the Learn Terraform variables GitHub repository for this tutorial.

$git clone https://github.com/hashicorp/learn-terraform-variables.git

Change to the repository directory.

$cd learn-terraform-variables

The configuration in defines a web application, including a VPC, load balancer, and EC2 instances.

Initialize this configuration.

$terraform init

Now apply the configuration.

$terraform apply

Respond to the confirmation prompt with a to create the example infrastructure.

»Parameterize your configuration

Variable declarations can appear anywhere in your configuration files. However, we recommend putting them into a separate file called to make it easier for users to understand how the configuration is meant to be customized.

To parameterize an argument with an input variable, you will first define the variable in , then replace the hardcoded value with a reference to that variable in your configuration.

Add a block declaring a variable named to .

variable "aws_region" {description="AWS region"type= string default="us-west-2"}

Variable blocks have three optional arguments.

  • Description: A short description to document the purpose of the variable.
  • Type: The type of data contained in the variable.
  • Default: The default value.

We recommend setting a description and type for all variables, and setting a default value when practical.

If you do not set a default value for a variable, you must assign a value before Terraform can apply the configuration. Terraform does not support unassigned variables. You will see some of the ways to assign values to variables later in this tutorial.

Variable values must be literal values, and cannot use computed values like resource attributes, expressions, or other variables.

You can refer to variables in your configuration with .

Edit the provider block in to use the new variable.

provider "aws" {- region = "us-west-2"+ region = var.aws_region}

Add a declaration for the variable to .

variable "vpc_cidr_block" {description="CIDR block for VPC"type= string default="10.0.0.0/16"}

Now, replace the hard-coded value for the VPC's CIDR block with a variable in .

module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "2.66.0"- cidr = "10.0.0.0/16"+ cidr = var.vpc_cidr_block ## ...}

Apply the updated configuration. Since the default values of these variables are the same as the hard-coded values they replaced, Terraform will perform no changes.

$terraform apply

Since the apply will make no changes to your resources, you can either respond to the confirmation prompt with a , or cancel the apply.

»Set the number of instances

Terraform supports several variable types in addition to .

Use a type to define the number of instances supported by this configuration. Add the following to .

variable "instance_count" {description="Number of instances to provision."type= number default=2}

Update EC2 instances to use the variable in .

module "ec2_instances" { source = "./modules/aws-instance"- instance_count = 2+ instance_count = var.instance_count ## ...}

When Terraform interprets values, either hard-coded or from variables, it will convert them into the correct type if possible. So the variable would also work using a string () instead of a number (). We recommend using the most appropriate type in variable definitions to helps users of your configuration know the appropriate data type to use, as well as to catch configuration errors early.

»Toggle VPN gateway support

In addition to strings and numbers, Terraform supports several other variable types. A variable with type represents true/false values.

Use a type variable to control whether your VPC is configured with a VPN gateway. Add the following to .

variable "enable_vpn_gateway" {description="Enable a VPN gateway in your VPC."type= bool default=false}

Use this new variable in your VPC configuration by editing as follows.

module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "2.44.0" ## ... enable_nat_gateway = true- enable_vpn_gateway = false+ enable_vpn_gateway = var.enable_vpn_gateway ## ...}

Leave the value for hard-coded. In any configuration, there may be some values that you want to allow users to configure with variables and others you don't.

When you write Terraform modules you intend to re-use, you will usually want to make as many attributes configurable with variables as possible, to make your module more flexible for use in more situations.

When you write Terraform configuration for a specific project, you may choose to leave some attributes with hard-coded values when it doesn't make sense to allow users to configure them.

»List public and private subnets

The variables you have used so far have all been single values. Terraform calls these types of variables simple. Terraform also supports collection variable types that contain more than one value. Terraform supports several collection variable types.

  • List: A sequence of values of the same type.
  • Map: A lookup table, matching keys to values, all of the same type.
  • Set: An unordered collection of unique values, all of the same type.

In this tutorial, you will use lists and a map, which are the most commonly used of these types. Sets are useful when a unique collection of values is needed, and the order of the items in the collection does not matter.

A likely place to use list variables is when setting the and arguments for the VPC. Make this configuration easier to use while still being customizable by using lists along with the function.

Add the following variable declarations to .

variable "public_subnet_count" {description="Number of public subnets."type= number default=2}variable "private_subnet_count" {description="Number of private subnets."type= number default=2}variable "public_subnet_cidr_blocks" {description="Available cidr blocks for public subnets."type= list(string) default=["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24", "10.0.4.0/24", "10.0.5.0/24", "10.0.6.0/24", "10.0.7.0/24", "10.0.8.0/24", ]}variable "private_subnet_cidr_blocks" {description="Available cidr blocks for private subnets."type= list(string) default=["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24", "10.0.104.0/24", "10.0.105.0/24", "10.0.106.0/24", "10.0.107.0/24", "10.0.108.0/24", ]}

Notice that the type for the list variables is . Each element in these lists must be a string. List elements must all be the same type, but can be any type, including complex types like and .

Like lists and arrays used in most programming languages, you can refer to individual items in a list by index, starting with 0. Terraform also includes several functions that allow you to manipulate lists and other variable types.

Use the function to get a subset of these lists.

The Terraform command opens an interactive console that you can use to evaluate expressions in the context of your configuration. This can be very useful when working with and troubleshooting variable definitions.

Open a console with the command.

$terraform console>

Now use the Terraform console to inspect the list of private subnet blocks.

Refer to the variable by name to return the entire list.

> var.private_subnet_cidr_blocks tolist([ "10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24", "10.0.104.0/24", "10.0.105.0/24", "10.0.106.0/24", "10.0.107.0/24", "10.0.108.0/24", ])

Retrieve the second element from the list by index with square brackets.

> var.private_subnet_cidr_blocks[1] "10.0.102.0/24"

Now use the function to return the first three elements from the list.

> slice(var.private_subnet_cidr_blocks, 0, 3) tolist([ "10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24", ])

The function takes three arguments: the list to slice, the start index, and the end index (exclusive). It returns a new list with the specified elements copied ("sliced") from the original list.

Leave the console by typing or pressing .

Now use the slice function to extract a subset of the cidr block lists in when defining your VPC's public and private subnet configuration.

module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "2.44.0" cidr = "10.0.0.0/16" azs = data.aws_availability_zones.available.names- private_subnets = ["10.0.101.0/24", "10.0.102.0/24"]- public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]+ private_subnets = slice(var.private_subnet_cidr_blocks, 0, var.private_subnet_count)+ public_subnets = slice(var.public_subnet_cidr_blocks, 0, var.public_subnet_count) ## ...}

This way, users of this configuration can specify the number of public and private subnets they want without worrying about defining CIDR blocks.

»Map resource tags

Each of the resources and modules declared in includes two tags: and . Assign these tags with a variable type.

Declare a new variable for resource tags in .

variable "resource_tags" {description="Tags to set for all resources"type= map(string) default={project="project-alpha", environment="dev"}}

Setting the type to tells Terraform to expect strings for the values in the map. Map keys are always strings. Like dictionaries or maps from programming languages, you can retrieve values from a map with the corresponding key. See how this works with the Terraform console.

Start the console.

$terraform console>

Retrieve the value of the key from the map.

> var.resource_tags["environment"] "dev"

Leave the console by typing or pressing .

Note: The command loads your Terraform configuration only when it starts. Be sure to exit and restart the console to pick up your most recent changes.

Now, replace the hard coded tags in with references to the new variable.

- tags = {- project = "project-alpha",- environment = "dev"- }+ tags = var.resource_tags ## ... replace all five occurrences of `tags = {...}`

The hard-coded tags are used five times in this configuration, be sure to replace them all.

Apply these changes.

$terraform apply

Since the value of the tag has changed, there will be changes to apply. Respond to the prompt with to apply them.

Lists and maps are collection types. Terraform also supports two structural types. Structural types have a fixed number of values that can be of different types.

  • Tuple: A fixed-length sequence of values of specified types.
  • Object: A lookup table, matching a fixed set of keys to values of specified types.

»Assign values to variables

Terraform requires that every variable be assigned a value. Terraform supports several ways to assign variable values.

»Assign values when prompted

In the examples so far, all of the variable definitions have included a default value. Add a new variable without a default value to .

variable "ec2_instance_type" {description="AWS EC2 instance type."type= string }

Replace the reference to the EC2 instance type in .

module "ec2_instances" { source = "./modules/aws-instance" instance_count = var.instance_count- instance_type = "t2.micro"+ instance_type = var.ec2_instance_type ## ...}

Apply this configuration now.

$terraform applyvar.ec2_instance_type AWS EC2 instance type. Enter a value: t2.microrandom_string.lb_id: Refreshing state... [id=3Bn]module.vpc.aws_vpc.this[0]: Refreshing state... [id=vpc-06083988d1c86b823]## ...Apply complete! Resources: 0 added, 0 changed, 0 destroyed.Outputs:public_dns_name = "lb-3Bn-project-alpha-dev-542453763.us-west-2.elb.amazonaws.com"

Terraform will prompt you for a value for the new variable. Enter .

Since the value you entered is the same as the old value, there will be no changes to apply.

»Assign values with a file

Whenever you execute a plan, destroy, or apply with any variable unassigned, Terraform will prompt you for a value. Entering variable values manually is time consuming and error prone, so Terraform provides several other ways to assign values to variables.

Create a file named with the following contents.

resource_tags={project="new-project", environment="test", owner="[email protected]"}ec2_instance_type="t3.micro"instance_count=3

Terraform automatically loads all files in the current directory with the exact name or matching . You can also use the flag to specify other files by name.

These files use syntax similar to Terraform configuration files (HCL), but they cannot contain configuration such as resource definitions. Like Terraform configuration files, these files can also contain JSON.

Apply the configuration with these new values.

$terraform apply

Respond to the confirmation prompt with to apply these changes.

You can also set input variables via environment variables and command line flags. Check out the documentation for more details. If there are different values assigned for a variable through these methods, Terraform will use the last value it finds, in order of precedence.

»Interpolate variables in strings

Terraform configuration supports string interpolation — inserting the output of an expression into a string. This allows you to use variables, local values, and the output of functions to create strings in your configuration.

Update the names of the security groups to use the project and environment values from the map.

module "app_security_group" { source = "terraform-aws-modules/security-group/aws//modules/web" version = "3.12.0"- name = "web-sg-project-alpha-dev"+ name = "web-sg-${var.resource_tags["project"]}-${var.resource_tags["environment"]}" ## ...}module "lb_security_group" { source = "terraform-aws-modules/security-group/aws//modules/web" version = "3.12.0"- name = "lb-sg-project-alpha-dev"+ name = "lb-sg-${var.resource_tags["project"]}-${var.resource_tags["environment"]}" ## ...}module "elb_http" { source = "terraform-aws-modules/elb/aws" version = "2.4.0" # Ensure load balancer name is unique- name = "lb-${random_string.lb_id.result}-project-alpha-dev"+ name = "lb-${random_string.lb_id.result}-${var.resource_tags["project"]}-${var.resource_tags["environment"]}" ## ...}

»Validate variables

This configuration has a potential problem. AWS load balancers have naming restrictions. They must be no more than 32 characters long, and can only contain a limited set of characters.

One way to deal with this is to use variable validation to restrict the possible values for the project and environment tags.

Replace your existing variable in with the below code snippet, which includes validation blocks to enforce character limits and character sets on both and values.

variable "resource_tags" {description="Tags to set for all resources"type= map(string) default={project="my-project", environment="dev"}validation{condition= length(var.resource_tags["project"]) <=16 && length(regexall("[^a-zA-Z0-9-]", var.resource_tags["project"])) ==0error_message="The project tag must be no more than 16 characters, and only contain letters, numbers, and hyphens."}validation{condition= length(var.resource_tags["environment"]) <=8 && length(regexall("[^a-zA-Z0-9-]", var.resource_tags["environment"])) ==0error_message="The environment tag must be no more than 8 characters, and only contain letters, numbers, and hyphens."}}

The function takes a regular expression and a string to test it against, and returns a list of matches found in the string. In this case, the regular expression will match a string that contains anything other than a letter, number, or hyphen.

This way the maximum length of the load balancer name will never exceed 32, and it will not contain invalid characters. Using variable validation can be a good way to catch configuration errors early.

Apply this change to add validation to these two variables. There will be no changes to apply, since your infrastructure configuration has not changed.

$terraform apply

Now test the validation rules by specifying an environment tag that is too long. Notice that the command will fail and return the error message specified in the validation block.

$terraform apply -var='resource_tags={project="my-project",environment="development"}'Error: Invalid value for variable on variables.tf line 69: 69: variable "resource_tags" {The environment tag must be no more than 8 characters, and only containletters, numbers, and hyphens.This was checked by the validation rule at variables.tf:82,3-13.

»Clean up your infrastructure

Now you have defined and used Terraform variables. By adding variables to your configuration, you have made it easier to make changes to your resources, such as adding more subnets or EC2 instances. Variables also make it easier for you to re-use this configuration for other projects, or turn it into a module that can be consumed by other Terraform configuration. You have also made this configuration more generic, allowing you to save project-specific configuration into the file.

Before moving on, destroy the infrastructure you created by running the command. Remember to confirm your destroy with a .

$terraform destroy

»Next steps

Now that you have seen how to define and use variables, check out the following resources for more information.

Sours: https://learn.hashicorp.com/tutorials/terraform/variables?in=terraform/cli


399 400 401 402 403