Automating NSG rules with an external IP in Terraform

For some time, I have been using Terraform to create environments – and it’s something I rely on heavily for my own Azure lab environment. My lab is an ever changing picture – and thus I regularly create and destroy resources and environments, to test new things. I usually just run Terraform locally and have it spin up specific lab environments as and when I need them.

One thing I often do to make my lab environments easy to access is enable RDP directly to VMs – obviously this is something to be avoided in production, but very useful for quick and easy access in a lab or test environment. I have a standard home broadband connection – so my IP sometimes changes, which can make managing NSG rules challenging, and no one wants to update lab scripts when it can be avoided with an easy solution!

This code is also available in my GitHub repo: Terraform-Azure/Automatic-ClientIP-NSG

To make this more secure and easy, you can create a data source within Terraform, and then use this during deployment, so that the NSG rule is created dynamically. To do this, we use a data source in our code, and a URL from an IP check service:

#Get Client IP Address for NSG
data "http" "clientip" {
  url = "https://ipv4.icanhazip.com/"
}

We can then use this when creating NSGs within Terraform – see line 15 where the external IP is used dynamically:

#Create NSG for dc01
resource "azurerm_network_security_group" "dc01-nsg" {
  name                = "dc01-nsg"
  location            = var.loc1
  resource_group_name = azurerm_resource_group.rg2.name

  security_rule {
    name                       = "RDP-In"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "*"
    source_port_range          = "*"
    destination_port_range     = "3389"
    source_address_prefix      = "${chomp(data.http.clientip.body)}/32"
    destination_address_prefix = "*"
  }

  tags  = {
    Environment  = var.Environment_tag
    CreatedBy    = var.CreatedBy_tag
  }
}

Once this resource has been deployed, the external IP at the time the Terraform was run will be included in the NSG. (IP address obscured below):

This is quick way to provide an automated NSG rule based on the external IP of the machine running Terraform. Any changes to the rule in the NSG done outside of Terraform, or changes to your client IP address will be updated when Terraform is run again. Thanks for reading – hope this helps! 🙂