更新时间:2023-05-23 GMT+08:00
分享

输出变量

输出变量可以理解为模块的返回值,通过关键字 "output" 进行声明。输出变量是一种对外公开某些信息的方法,既可以在根模块中运行 terraform apply/output 命令输出特定的值,又可以在子模块中将资源的属性值提供给父模块。

声明输出变量

按照约定,输出变量通常在名为 variables.tf 的文件中定义。输出变量通过“output”关键字进行声明:

output "ecs_address" {
  value       = huaweicloud_compute_instance.myinstance.network[0].fixed_ip_v4
  description = "The private IP address of my ECS"
}

output 关键字后的标签为输出变量的名称,该名称必须是有效的标识符。output块中主要包括以下参数:

  • value:必选项,输出变量的值,任何有效的表达式都可作为输出使用。
  • description:输出变量的描述信息,用于描述输出变量的用途。
    output "vpc_id" {
      value       = huaweicloud_vpc.myvpc.id
      description = "Check out the VPC ID"
    }
    
    $ terraform output
    vpc_id = df507d37-bce2-4750-8873-f62abb3b085c
  • sensitive:将输出变量标记为敏感项,在 CLI 中将隐藏输出变量值的显示。
    output "vpc_id" {
      value       = huaweicloud_vpc.myvpc.id
      description = "Check out the VPC ID"
      sensitive   = true
    }
    
    $ terraform output
    vpc_id = <sensitive>

    注意:标记为敏感项的输出变量在输出时会自动被隐藏,但其输出值仍然可以通过以下方式可见:

    • 输出变量的值记录在 state 文件中,其值对所有能够访问state 文件的用户均可见。
    • 子模块中敏感输出变量值被父模块调用,通过父模块的相关输出和资源引用后可以在CLI中显示。
  • depends_on:指定输出变量的依赖关系。由于输出变量只是导出数据的一种手段,因此通常不需要设置与其他资源、数据的依赖关系。
分享:

    相关文档

    相关产品