Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Input Variables

Updated on 2023-12-13 GMT+08:00

Input variables are like arguments for a module. They are declared using the keyword variable. By defining input variables, you can flexibly modify the configuration without altering the source code of the module. You can use default values, CLI options, or environment variables to set the input variables' values.

Defining Input Variables

By convention, input variables are defined in a file named variables.tf. The input variable is declared using the keyword variable:

variable "iamge_id" {
  type        = string
  description = "image id of Ubuntu 1804"
}

variable "availability_zone_name" {
  type    = string
  default = 
}
The label after the variable keyword is the name of the input variable, which must be unique among all variables in the same module. The name of a variable can be any valid identifier other than a reserved keyword. The reserved keywords include:
source    version    providers    count    for_each    lifecycle    depends_on    locals

A variable block contains the following arguments:

  • type: specifies the type of a variable. The default value is string.
  • description: describes the usage of a variable.
  • default: specifies the default value of a variable. A variable with a default value can be regarded as an optional variable.
  • validation block: specifies the customized validation rules of a variable.

If no variable type is specified, the default value string is used. You are advised to explicitly specify variable types; they can serve as helpful reminders for users of the module, and they allow Terraform to return a helpful error message if the wrong type is used. Terraform input variables support the following types:

  • Basic types: string, number, and bool
  • Compound types: list(<TYPE>), set(<TYPE>), map(<TYPE>)

The following example defines a variable of the compound type:

variable "availability_zone_names" {
  type    = list(string)
  default = []
}

variable "docker_ports" {
  type = list(object({
    internal = number
    external = number
    protocol = string
  }))
  default = [{
    internal = 8300
    external = 8300
    protocol = "tcp"
  }]
}

Custom Validation Rules

You can use the validation nested block to specify custom validation rules for an input variable. This feature is supported in Terraform 0.13.0 and later versions. Example:

variable "iam_user_password" {
    type        = string
    description = "The password for iam user to log in."

    validation {
      condition     = length(var.iam_user_password)>=8
      error_message = "The password is too short."
    }
}

The condition argument is a Boolean expression. You can use a can function to check whether an error will be caused by the expression. Example:

variable "iam_user_name" {
    type        = string
    description = "This name is used for iam user to log in."

    validation {
      # regex(...) If the variable fails to match the following condition, an error is returned.
      condition     = can(regex("([a-zA-Z])", var.iam_user_name))
      error_message = "Incorrect user name. Please check whether it contains upper and lower case letters."
    }
}

If the result of condition is false, Terraform generates an error message that contains the character string defined by error_message. The value of error_message must include at least a complete sentence that starts with an uppercase letter and ends with a period (.) or question mark (?).

Referencing Input Variables

An input variable can be accessed as var.<Variable name> and only in the module that declares it.

# variables.tf
variable "vpc_cidr" {
  type        = string
  description = "the CIDR of VPC"
}

# main.tf

Setting Variables

You can set input variables in either of the following ways:

  • With the -var command line option.
  • In variable definitions (.tfvars) files, either specified on the command line or automatically loaded.
  • As environment variables.

Variable Definitions (.tfvars) Files

If many variables are used in the configuration, you are advised to set their values in a variable definitions file, and then use the -var-file option to specify that file.

terraform apply -var-file="testing.tfvars"

A variable definitions (.tfvars) file uses the same basic syntax as the configuration files, but consists only of variable name assignments:

vpc_name = "my_vpc"
vpc_cidr = "192.168.0.0/16"
availability_zone_names = [
]

Terraform also automatically loads variable definitions files if they are present:

  • Files named exactly terraform.tfvars or terraform.tfvars.json
  • Any files with names ending in .auto.tfvars or .auto.tfvars.json

Files whose names end with .json are parsed instead as JSON objects.

{
    "vpc_name": "my_vpc"
}

Variable Definition Precedence

The above mechanisms for setting variables can be used together in any combination. For variables of the compound type, you are advised to use the variable definitions file to improve readability and avoid problems caused by escape. If you assign multiple values to the same variable, Terraform uses the last value it finds, overriding any previous values. Terraform loads variables in the following order, with later sources taking precedence over earlier ones:

  1. Environment variables
  2. terraform.tfvars or terraform.tfvars.json file
  3. *.auto.tfvars or *.auto.tfvars.json file
  4. -var and -var-file options in the command line

Note that the same variable cannot be assigned multiple values within a single source.

For more information about variables, see Input Variables in the Terraform documentation.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback