Reputation: 21
I need to create a module based application with Terraform in Azure.
Basically I need the above but using modules for both the subnet and the network security group like this : (Network security group would contain the association)
main.tf (root)
modules
networksecuritygroup
main.tf
variable.tf
subnet
main.tf
output.tf
variable.tf
I am not sure how to create a reference at the subnet_id section of the network security group association at the NSG module to the already existing subnet module's subnet ID.
This part gets me thinking :
subnet_id = azurerm_subnet.example.id
Should look something like this maybe?
subnet_id = var.subnetname.id?
I can't get it work and I couldn't find anything similar like this, only a resource group and storage account association but that is different as no ID needed there...
Upvotes: 2
Views: 2243
Reputation: 7820
I am not sure how to create a reference at the subnet_id section of the network security group association at the NSG module to the already existing subnet module's subnet ID.
Alternatively ,You can associate NSG with existing Subnet ID using terraform, you can use data block for using existing Subnet
.
provider "azurerm" {
features {}
}
data "azurerm_subnet" "venkatsubnet" {
name = "samplesubnet"
virtual_network_name = "Demosubnet"
resource_group_name = "<rg-name>"
}
# If you want to use an existing Virtual Network instead of creating a new Virtual Network, use the below data block for the Virtual Network.
#data "azurerm_virtual_network" "example" {
# name = "Demosubnet"
#resource_group_name = "<rg-name>"
#}
resource "azurerm_virtual_network" "example" {
name = "example-network"
address_space = ["10.0.0.0/16"]
location = data.azurerm_resource_group.venkatrg.location
resource_group_name = data.azurerm_resource_group.venkatrg.name
}
resource "azurerm_network_security_group" "samplensg" {
name = "example-nsg"
location = data.azurerm_resource_group.venkatrg.location
resource_group_name = data.azurerm_resource_group.venkatrg.name
security_rule {
name = "test123"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_subnet_network_security_group_association" "example" {
subnet_id = data.azurerm_subnet.venkatsubnet.id
network_security_group_id = azurerm_network_security_group.samplensg.id
}
output "subnet_id" {
value = data.azurerm_subnet.venkatsubnet.id
}
Terraform apply:
After running the above code, the Subnet is associated with the NSG in portal as shown below.
Reference: Azure network - Subnet.
Upvotes: 0