我通过以下方式声明了安全组:
resource "azurerm_network_security_group" "wan" {
count = "${var.enable_wan_subnet ? 1 : 0}"
provider = "azurerm.base"
name = "${format("%s-%s", var.environment_name, "WAN-Subnet-Security-Group")}"
location = "${azurerm_resource_group.this.location}"
resource_group_name = "${azurerm_resource_group.this.name}"
tags = "${
merge(map("Name", format("%s-%s-%s",var.environment_name,"WAN-Subnets", "Security-Group")),
var.tags_global,
var.tags_module)
}"
}
并为该安全组创建输出:
output "security_groups_id_wan" {
value = "${azurerm_network_security_group.wan.*.id}"
depends_on = [
"azurerm_subnet.wan",
]
}
在输出中我得到
实际输出
security_groups_id_wan = [
/subscriptions/111-222-333-4445/resourceGroups/default_resource_group/providers/Microsoft.Network/networkSecurityGroups/DF-DTAP-WAN-Subnet-Security-Group
]
如何从输出中删除除资源名称(DF-DTAP-WAN-Subnet-Security-Group)以外的所有内容
所需的输出:
security_groups_id_wan = [
DF-DTAP-WAN-Subnet-Security-Group
]
答案 0 :(得分:0)
您用"${format("%s-%s", var.environment_name, "WAN-Subnet-Security-Group")}"
自己建立了该名称,那么为什么不输出该名称呢?
要避免重复,您可以将其放在本地并在资源和输出中引用它:
locals {
security_group_name = "${format("%s-%s", var.environment_name, "WAN-Subnet-Security-Group")}"
}
resource "azurerm_network_security_group" "wan" {
count = "${var.enable_wan_subnet ? 1 : 0}"
provider = "azurerm.base"
name = "${local.security_group_name}"
# ...
}
output "security_groups_id_wan" {
value = "${local.security_group_name}"
}
请注意,您也不需要depends_on
,因为a)它是输出,无论如何它都是在末尾发生的; b)您已经对该资源具有隐式依赖性,因为您使用了插值包括了资源。
您可以通过Hashicorp Learn platform阅读有关Terraform依赖关系的更多信息。
答案 1 :(得分:0)
您可以只使用Terraform函数并按以下方式更改输出值:
output "security_groups_id_wan" {
value = "${slice(split("/",azurerm_network_security_group.wan.*.id), length(split("/",azurerm_network_security_group.wan.*.id))-1, length(split("/",azurerm_network_security_group.wan.*.id)))}"
depends_on = [
"azurerm_subnet.wan",
]
}
使用这些功能,可以根据需要输出所有资源。有关更多详细信息,请参见Terraform Supported built-in functions。
更新
通过Terraform数据和此处的模板对现有NSG进行测试:
data "azurerm_network_security_group" "test" {
name = "azureUbuntu18-nsg"
resource_group_name = "charles"
}
output "substring" {
value = "${slice(split("/",data.azurerm_network_security_group.test.id), length(split("/",data.azurerm_network_security_group.test.id))-1, length(split("/",data.azurerm_network_security_group.test.id)))}"
}
此处的结果屏幕截图:
答案 2 :(得分:0)
@Charles Xu的答案的补充:必须先将列表转换为字符串
output "subnets_id_wan" {
value = "${slice(split("/",join(",",azurerm_subnet.wan.*.id)), length(split("/",join(",",azurerm_subnet.wan.*.id)))-1, length(split("/",join(",",azurerm_subnet.wan.*.id))))}"
depends_on = [
"azurerm_subnet.wan",
]
}