Mostra la pàginaRevisions anteriorsQuè hi enllaçaExporta a PDFTorna dalt Aquesta pàgina és només de lectura. Podeu veure'n el codi font, però no podeu canviar-la. Consulteu el vostre administrador si penseu que això és degut a algun error. = terraform variables * [[https://developer.hashicorp.com/terraform/tutorials/configuration-language/variables]] == declaración * recomendado en fichero aparte **variables.tf** declaración: <code properties variables.tf> variable "aws_region" { description = "AWS region" type = string default = "us-west-2" } variable "instance_count" { description = "Number of instances to provision." type = number default = 2 } variable "enable_vpn_gateway" { description = "Enable a VPN gateway in your VPC." type = bool default = false } variable "resource_tags" { description = "Tags to set for all resources" type = map(string) default = { project = "project-alpha", environment = "dev" } } </code> uso: <code properties> provider "aws" { region = var.aws_region } module "ec2_instances" { source = "./modules/aws-instance" depends_on = [module.vpc] instance_count = var.instance_count #tags = { # project = "project-alpha", # environment = "dev" #} tags = var.resource_tags } </code> == list, map, set * **list**: lista de valores del mismo tipo, retornados en el mismo orden. * Admite el uso de varios tipos: ''list(string)'', ''list(list)'', ''list(map)'', ... * <code properties>list("a", "b", "c") # <=0.11</code> * <code properties>["a", "b", "c"] # >=0.12</code> * <code properties>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", ] }</code> * **map**: colección de valores key=value, identificado cada uno con una cadena * <code properties>map("a", "b", "c", "d") { "a" = "b" "c" = "d" }</code> * <code properties>{"a" = "b", "c" = "d"} { "a" = "b" "c" = "d" }</code> * **set**: colección de __valores únicos__ sin identificadores secundarios y sin orden === funciones * [[https://developer.hashicorp.com/terraform/language/functions/slice|slice()]]: obtener parte de una lista. == más tipos * **object**: colección de atributos identificados, con posibilidad de diferentes tipos * <code javascript>{ name = "John" age = 52 }</code> * <code ruby>variable "wks_rg_name" { type = object({ pre = string, int = string, default = string }) } wks_rg_name = { pre = "prepre", int = "intint", default = "" } resource "azurerm_resource_group" "rg" { name = "rg1-rg-${var.wks_rg_name[terraform.workspace]}" location = "${var.location}" }</code> * **tuple**: colección de elementos consecutiva de diferentes tipos * <code properties>["a", 15, true]</code> /via: [[https://www.terraform.io/docs/configuration/types.html]] == input variables * bloque declaración/valor por defecto:<code properties> variable "image_id" { type = string } variable "availability_zone_names" { type = list(string) default = ["us-west-1a"] } variable "docker_ports" { type = list(object({ internal = number external = number protocol = string })) default = [ { internal = 8300 external = 8300 protocol = "tcp" } ] } </code> * type (constraints) = bool, number, string, list(), set(), map(), object(), tuple([...]) * default * description * validation {condition,error_message} -> en pruebas * uso:<code properties>var.<NOMBRE_DECLARATIVO></code> == interpolación <code properties> name = "web-sg-${var.resource_tags["project"]}-${var.resource_tags["environment"]}" </code> == validación <code properties> 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"])) == 0 error_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"])) == 0 error_message = "The environment tag must be no more than 8 characters, and only contain letters, numbers, and hyphens." } } </code> == asignación de valores en variables del módulo raiz (Root Module) * mediante parámetro en el cli ''-var='<KEY>="<VALUE>"%%'%%'' * usando ficheros de definición de variables: **%%*%%.tfvars** o **%%*%%.tfvars.json** * que se pueden cargar automáticamente<code properties>image_id = "ami-abc123" availability_zone_names = [ "us-east-1a", "us-west-1c", ]</code> * **terraform.tfvars** o **terraform.tfvars.json** * **%%*%%.auto.tfvars** o **%%*%%.auto.tfvars.json** * o especificado como parámetro en el cli * en fichero específico ''-var-file="<FILE.TFVARS>"'' * en el propio comando ''-var "server=web"'' * en estos ficheros solo se realiza la asignación de la variable * los ficheros acabados en JSON se parsean como objeto<code javascript>{ "image_id": "ami-abc123", "availability_zone_names": ["us-west-1a", "us-west-1c"] }</code> * variables de entorno: * cualquier variables que empiece por **TF_VAR_** * orden de preferencia (orden en el cargan, el posterior prevalece al anterior): - terraform.tfvars - terraform.tfvars.json - %%*%%.auto.tfvars o %%*%%.auto.tfvars, alfabéticamente - ''-var'' o ''-var-file'' == output como valores de retorno de un módulo o recurso === usos * usos * módulo hijo expone variables al módulo padre * exponer variables en el cli en la ejecución de ''terraform apply'' * cuando se usa **remote state**, los outputs pueden ser accesibles mediante **terraform_remote_state**:<code properties> data "terraform_remote_state" "vpc" { backend = "remote" config = { organization = "hashicorp" workspaces = { name = "vpc-prod" } } } # Terraform >= 0.12 resource "aws_instance" "foo" { # ... subnet_id = data.terraform_remote_state.vpc.outputs.subnet_id }</code> == declaración <code properties>output "instance_ip_addr" { value = aws_instance.server.private_ip }</code> * **description**: string * **sensitive**: [true | false] -> oculta valores sensibles de la salida por consola, pero los mantiene en el estado * cuando se usa estado remoto, este se guarda en le memoria local del equipo * ''terraform output [ [-j-son] [-no-color] [-state=<path_to_state_file>] ] <NOMBRE> * ''-state'' se ignora si se trabaja con **remote state** * ''terraform output password password = <sensitive>'' ¿? * **depends_on**: * list * como último recurso en caso de tener algún problema con esa variable y el orden de ejecución === acceso * mediante **module.output_name** == Local values * >=0.12 * <code properties>locals { service_name = "forum" owner = "Community Team" }</code> * <code properties>locals { # Ids for multiple sets of EC2 instances, merged together instance_ids = concat(aws_instance.blue.*.id, aws_instance.green.*.id) } locals { # Common tags to be assigned to all resources common_tags = { Service = local.service_name Owner = local.owner } }</code><code properties>resource "aws_instance" "example" { # ... tags = local.common_tags }</code> tech/terraform/variables.txt Darrera modificació: 10/06/2025 06:50per mate