【问题标题】:Can this unreadable terraform code-snippet be made more presentable?这个不可读的 terraform 代码片段可以变得更美观吗?
【发布时间】:2021-07-10 06:20:46
【问题描述】:

我有一个代码 sn-p 为 GKE 集群设置节点池名称,它非常不可读。我将不胜感激任何帮助,使其更形象和更容易理解正在发生的事情。

output "test" {
  value = regex("(?:[a-z](?:[-a-z0-9]{0,38}[a-z0-9])?)", lower(var.node_pool_version != "" ? var.node_pool_name != "" ? "${var.node_pool_name}-v${replace("${var.node_pool_version}",".","-")}" : "${var.name_prefix}-v${replace("${var.node_pool_version}",".","-")}" : var.node_pool_name != "" ? var.node_pool_name : "${var.name_prefix}-standard"))
}

variable "node_pool_version" {
  description = "Override node_version for cluster upgrades"
  type        = string
  default     = ""
}

variable "node_pool_name" {
  type    = string
  default = ""
}

variable "name_prefix" {
  type    = string
  default = "develop"
}

输出:

❯ terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

test = develop-standard
❯ terraform apply -var node_pool_version=1.16.15-gke.7800

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

test = develop-v1-16-15-gke-7800
❯ terraform apply -var node_pool_version=1.16.15-gke.7800 -var node_pool_name=develop-standard

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

test = develop-standard-v1-16-15-gke-7800

编辑: 我担心的是 String FunctionsConditional Expressions 的广泛使用来生成输出。我的用例是如果用户没有通过node_pool_versionnode_pool_name,我的输出仍然应该设法生成一个易于识别的节点名称。有没有更好的方法来重写这段代码,让 Terraform 新手更容易阅读?

【问题讨论】:

  • 你可以做多个输出,不是吗?
  • 添加了一些更清晰的我正在寻找的东西。

标签: terraform terraform0.12+ hcl


【解决方案1】:

我想你能做的最好的就是使用locals 块:

variable "node_pool_version" {
  description = "Override node_version for cluster upgrades"
  type        = string
  default     = ""
}

variable "node_pool_name" {
  type    = string
  default = ""
}

variable "name_prefix" {
  type    = string
  default = "develop"
}

locals {
  version            = replace("${var.node_pool_version}", ".", "-")
  prefix             = var.node_pool_name != "" ? var.node_pool_name : var.name_prefix
  id                 = var.node_pool_name != "" ? local.prefix : "${local.prefix}-standard"
  versioned_id       = local.version != "" ? "${local.prefix}-v${local.version}" : local.id
  clean_versioned_id = regex("(?:[a-z](?:[-a-z0-9]{0,38}[a-z0-9])?)", lower(local.versioned_id))
}

output "test" {
  value = local.clean_versioned_id
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多