# Create a Network Security Group (NSG) in Azure

In 
Published 2022-12-03

This tutorial explains how we can create a Network Security Group (NSG) in Azure using Terraform.

You can use an Azure Network Security Group (NSG) to filter network traffic between Azure resources in an Azure virtual network.

Here are the steps to follow in order to deploy a Network Security Group (NSG) in Azure using Terraform:

1) Create a folder where we keep our project

To be well organized we need to create a folder where we keep our project. In my case this is D:\terraform\azure\nsg.

2) Create the configuration file

Now is the time to tell Terraform what to do.

We create main.tf file with the following content:

#Set the Azure Provider source and version being used
#----------------------------------------------------
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.0.1"
    }
  }
}

# Configure the Microsoft Azure Provider
#---------------------------------------
provider "azurerm" {
  features {}
}

#####################################################
#   Create Network Security Group (NSG) and rules   #
#######################################################
resource "azurerm_network_security_group" "master1-nsg" {
    name                = "master1-nsg"
    location            = "West Europe"
    resource_group_name = "my-new-resource-group"

    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 = "*"
    }

    tags = {
        environment = "Dev"
    }
}

So, we configure the provider and a Network Security Group (NSG) for Azure.

3) Initialize the project

Run the terraform init command to initialize a working directory that contains a Terraform configuration. This command is run under the working/project directory.

terraform init

You will see the following in your console:

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/azurerm versions matching "3.0.1"...
- Installing hashicorp/azurerm v3.0.1...
- Installed hashicorp/azurerm v3.0.1 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

4) Login to the Azure account we work with using Azure CLI

az login

You will be prompted to login from the browser. Once the username/password are verified, you are connected to Azure in the console.

Run the following command and change the subscription name if you are using multiple subscriptions:

az account set --subscription "MyAzureSubscription1"

5) Create the Virtual NET in Azure

Now it is the time to create a Resource Group and a Virtual NET in Azure and this is done very simple using the following command:

terraform apply

You can see the result on the screen:

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
  + create

Terraform will perform the following actions:

  # azurerm_network_security_group.master1-nsg will be created
  + resource "azurerm_network_security_group" "master1-nsg" {
      + id                  = (known after apply)
      + location            = "westeurope"
      + name                = "master1-nsg"
      + resource_group_name = "my-new-resource-group"
      + security_rule       = [
          + {
              + access                                     = "Allow"
              + description                                = ""
              + destination_address_prefix                 = "*"
              + destination_address_prefixes               = []
              + destination_application_security_group_ids = []
              + destination_port_range                     = "22"
              + destination_port_ranges                    = []
              + direction                                  = "Inbound"
              + name                                       = "SSH"
              + priority                                   = 1001
              + protocol                                   = "Tcp"
              + source_address_prefix                      = "*"
              + source_address_prefixes                    = []
              + source_application_security_group_ids      = []
              + source_port_range                          = "*"
              + source_port_ranges                         = []
            },
        ]
      + tags                = {
          + "environment" = "Dev"
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

azurerm_network_security_group.master1-nsg: Creating...
azurerm_network_security_group.master1-nsg: Creation complete after 5s [id=/subscriptions/69045ea7-6500-45f7-adc6-b4c86ce7233b/resourceGroups/my-new-resource-group/providers/Microsoft.Network/networkSecurityGroups/master1-nsg]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

If you run terraform apply again you will see the following :

azurerm_network_security_group.master1-nsg: Refreshing state... [id=/subscriptions/69045ea7-6500-45f7-adc6-b4c86ce7233b/resourceGroups/my-new-resource-group/providers/Microsoft.Network/networkSecurityGroups/master1-nsg]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are
needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

That means terraform apply command is idempotent.