如何在Terraform的模块中引用Azure网络安全ID?

时间:2018-12-17 21:06:50

标签: terraform

我不确定如何在模块中引用一个Azure网络安全组。我创建了一个模块,可以对创建的任何VM重新使用,该模块在一定程度上可以正常工作,除非我不确定如何为其分配网络安全组ID。下面是一个示例(稍作修改,我身上没有),非常接近我所拥有的基础。

main.tf根目录

module "vm1" {
source = "/modules/vm/"
NSG = ????
}

tfvars

nic_name = apache_vm_nic
location = West Europe
........

modules / vm / main.tf

.........

resource "azurerm_network_interface" "myterraformnic" {
name                = "var.nic_name"
location            = "var.location"
resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"
network_security_group_id = { WHAT DO I PUT HERE? }

ip_configuration {
    name                          = "myNicConfiguration"
    subnet_id                     = "${azurerm_subnet.myterraformsubnet.id}"
    private_ip_address_allocation = "dynamic"
    public_ip_address_id          = "${azurerm_public_ip.myterraformpublicip.id}"
}
}


resource "azurerm_network_security_group" "apache-nsg" {
name                = "myNetworkSecurityGroup"
location            = "eastus"
resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"

security_rule {
    name                       = "SSH"
    priority                   = 1001
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "22"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
}
}

resource "azurerm_network_security_group" "nginx-nsg" {
name                = "myNetworkSecurityGroup"
location            = "eastus"
resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"

security_rule {
    name                       = "SSH"
    priority                   = 1001
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "22"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
}
}

在network_security_group_id下的module / main.tf文件中,我无法准确地放置$ {azurerm_network_security_group.apache-nsg.id}或$ {azurerm_network_security_group.nginx-nsg.id}。那我该放些什么以便可以在所有VM上重用此模块?

谢谢

1 个答案:

答案 0 :(得分:0)

您的问题对我来说还不是很清楚,但是我将假设您要创建一个通用网络安全组,该组要分配给VM模块的多个实例。

如果要传递来自main.tf at root的安全组的ID,请执行以下操作: 在模块外部创建网络安全组资源,例如在main.tf at root内,就像您在VM模块内部创建了一些(用于Apache和Nginx)一样,因此main.tf at root看起来像这样:

resource "azurerm_network_security_group" "some_generic_vm_nsg" {
  ....
}

module "vm1" {
  source = "/modules/vm/"
  NSG = "${azurerm_network_security_group.some_generic_vm_nsg.id}"
}

请注意,我们现在将nsg的ID传递给您的VM模块实例。 但是,您的VM模块尚未声明NSG变量。因此,创建文件modules/vm/variables.tf并将其放入其中:

variable "NSG" {
  type = "string"
}

在模块内部,network_security_group_id = { WHAT DO I PUT HERE? }变为:

network_security_group_id = "${var.NSG}"

这样,您可以将同一网络安全组分配给多个VM模块实例。

您可以study this documentation以获取更多详细信息。