azure - terraform azurerm_virtual_machine_extension 设置上的动态 block

标签 azure terraform terraform-provider-azure terraform0.12+

我正在使用 terraform 创建 Azure VM 扩展资源 azurerm_virtual_machine_extension。但是,我陷入了以下用例,是否可以动态创建 settings block ?

variable "test_string" {
  description = "boolean var to attach VM nics to lb"
  type        = string
  default     = ""
}

variable "test_script" {
  description = "script locally"
  type        = string
  default     = ""
}

variable "file_uri" {
  description = "script to download"
  type        = string
  default     = "https://example.com/azure-tests/custom_script.sh"
}


resource "azurerm_virtual_machine_extension" "ama_vm_extension" {

  name                 = "tst-vm-extension"
  virtual_machine_id   = "xxxxx-xxxx-xxxxx"
  publisher            = "Microsoft.Azure.Extensions"
  type                 = "CustomScript"
  type_handler_version = "2.0"

  dynamic settings = <<SETTINGS
  {
    count = var.file_uri != "" ? 1: 0
    "commandToExecute": "sh ${basename(var.file_uri)}",
    "fileUris": ["${var.file_uri}"]
  }
  SETTINGS

  dynamic settings = <<SETTINGS
  {
     count = var.test_string != "" ? 1: 0
     content {
       "commandToExecute": "${var.test_string}"
     }
  }
  SETTINGS

  dynamic settings = <<SETTINGS
  {
     count = var.test_script != "" ? 1: 0
     content {
       "script": "${base64encode(var.test_string)}"
     }
  }
  SETTINGS

}

在上面的代码中,我想使用 test_stringtest_scriptfile_uri 变量控制资源行为。但是,terraform 只允许资源中存在一个 settings block ,我不知道如何使用 dynamic block 功能在这里。因为我们最后有 SETTINGS 字符串。

非常感谢您的帮助。

谢谢, 戒律

最佳答案

Terraform 的动态 block 旨在与资源中的嵌套 block 一起使用。由于 setting 只是一个字符串,因此您可以使用常规条件来设置 setting 的值。

我可能会做这样的事情:

locals {
  file_uri_settings = jsonencode({
    "commandToExecute" = "sh ${basename(var.file_uri)}",
    "fileUris"         = [var.file_uri]
  })
  test_string_settings = jsonencode({
    "commandToExecute" = var.test_string
  })
  test_script_settings = jsonencode({
    "script" = base64encode(var.test_script)
  })
}

resource "azurerm_virtual_machine_extension" "example" {
  // ...
  settings = var.test_string != "" ? local.test_string_settings : (var.test_script != "" ? local.test_script_settings : local.file_uri_settings)
  // ...
}

为了清理它,我将不同的选项拉到本地 block 中。然后您可以链接三元运算符来选择要使用的正确字符串。

关于azure - terraform azurerm_virtual_machine_extension 设置上的动态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63564464/

相关文章:

azure - Power BI - 事件中心中的 DAX 速度缓慢

terraform - 跳过内联脚本内的地形插值

azure - 将 Terraform azure 状态文件置于不同的订阅下

azure - Windows 代理池只能使用 Azure-CNI 添加到 AKS 群集

terraform - 将数据作为变量传递给 Terraform 模块

sql - 无法引用其他数据库中的表创建存储过程

azure - 使用 Windows Azure 共享网站托管根域 (mydomain.com)?

c# - Microsoft Graph API 访问 token

terraform - 错误刷新状态 : state data in S3 does not have the expected content

azure - Terraform 配置程序无法 winrm 到 Azure 上新建的 Windows VM