【问题标题】:How to filter data from locals based on if else condition terraform?如何根据 if else 条件 terraform 过滤来自本地人的数据?
【发布时间】:2021-06-02 19:42:28
【问题描述】:

Main.tf

locals {
    location_mapping = [
    {
        "url": "L1.tfe.com"
        "location": "L1"
        "resource_group_name": "R1"
        "name_log_workspace_name": "W1"
    },
    {
        "url": "L2.tfe.com"
        "location": "L2"
        "resource_group_name": "R2"
        "name_log_workspace_name": "W2"
    },
    {
        "url": "L3.tfe.com"
        "location": "L3"
        "resource_group_name": "R3"
        "name_log_workspace_name": "W3"
    }
    ]
}

data "azurerm_log_analytics_workspace" "example" {
    # Populate name and resource group based on var.location(L2) condition if location matches in locals
    name                = "W2"
    resource_group_name = "R2"
}

我想根据本地数据块中的 location and url 条件动态填充 nameresource_group_name。

例子

如果我通过location value L2url value L2.tfe.com,那么我将得到name=W2resource_group_name=R2

【问题讨论】:

    标签: terraform terraform-provider-azure azure-rm terraform-template-file hashicorp


    【解决方案1】:

    我认为以下内容应该是合适的,假设只能有一个匹配项:

    variable "location" {
      default = "L2"
    }
    
    variable "url" {
      default = "L2.tfe.com"
    }
    
    locals {
        location_mapping = [
        {
            "url": "L1.tfe.com"
            "location": "L1"
            "resource_group_name": "R1"
            "name_log_workspace_name": "W1"
        },
        {
            "url": "L2.tfe.com"
            "location": "L2"
            "resource_group_name": "R2"
            "name_log_workspace_name": "W2"
        },
        {name_log_workspace_name
            "url": "L3.tfe.com"
            "location": "L3"
            "resource_group_name": "R3"
            "name_log_workspace_name": "W3"
        }
        ]
        
       selected_mapping = lookup({for val in local.location_mapping:
                               0 => val if val.location == var.location  &&
                              val.url == var.url}, 0,
                           {
                                "url": "default"
                                "location": "default_L"
                                "resource_group_name": "default_R"
                                "name_log_workspace_name": "default_W"
                           })
        
    }
    
    data "azurerm_log_analytics_workspace" "example" {    
        name                = local.selected_mapping.name_log_workspace_name
        resource_group_name = local.selected_mapping.resource_group_name
    }
    

    【讨论】:

    • 嗨@Marcin 我需要匹配两个条件locationurl
    • @NaveenKumar 您可以将and 添加到if。我更新了答案。
    • 我需要 like if 条件不匹配然后我需要一些默认值来让我尝试使用 else 但出现错误。
    • @NaveenKumar 我再次更新了答案。但下一次,请在问题中提供所有这些详细信息。
    • @NaveenKumar 进展如何?
    猜你喜欢
    • 2023-03-29
    • 2021-09-25
    • 2016-02-11
    • 2019-04-25
    • 2023-01-24
    • 1970-01-01
    • 2018-10-08
    • 2018-10-04
    相关资源
    最近更新 更多