Script to create NSX tag, group and firewall rules

You are here:
< Back

This is a little script to assist in creating NSX items used for micro-segmenting an application.  It assumes that you have PowerCLI and PowerNSX already installed.  These rules are based on the suggestions provided in the VMware NSX Micro-Segmentation Day 2 book.

The script performs;

  • Creates an NSX tag and assigns it to the listed VM’s.
  • Creates a security group and includes the tag
  • Creates a new firewall section
  • Creates  firewall rules.  The rules are disabled so it won’t accidentally cause any issues.


# Jim Streit - jstreit@vmware.com
# Version 3.0

# connect to the NSX Manager
Connect-NsxServer -vCenterServer 192.168.1.111

# Application Name
$appname = "Books"

# Location / Data Center Name
$dc = "Chicago"

# VMs to assign security tag
$stvm = "tinyCore-162","tinyCore-163","tinyCore-164"

# ---- Do Not Edit Below ----

# security tag name
$st = "ST_" + $dc + "_" + $appname

# log tag name
$lt = $dc + "_" + $appname

# security group name
$sg = "SG_" + $dc + "_" + $appname

# firewall section name
$fs = "FP_" + $dc + "_" + $appname

# Create security tag and assign to VM's
New-NsxSecurityTag -Name $st
$stn = Get-NsxSecurityTag -Name $st
foreach ($vm in $stvm) {
get-vm -Name $vm | New-NsxSecurityTagAssignment -ApplyTag $stn
}

#Create security group and add the security tag as a member
New-NsxSecurityGroup -Name $sg
$app = Get-NsxSecurityTag -Name $st
Get-NsxSecurityGroup -Name $sg | Add-NsxSecurityGroupMember -Member $app

#Create firewall section
New-NsxFirewallSection -Name $fs
$sec = Get-NsxFirewallSection -Name $fs

#Create default firewall rules but leave them disabled
$sgn = Get-NsxSecurityGroup $sg
$dfwgrp = "FW_" + $appname + "_SG_SG_Allow"
$dfwany = "FW_" + $appname + "_Any_Any_Catch"
$catch = $appname + "_Catch"
Get-NsxFirewallSection -Name $fs | New-NsxFirewallRule -Name $dfwgrp -Source $sgn -Destination $sgn -Action allow -AppliedTo $sgn -EnableLogging -tag $appname -Position Bottom -Disabled
Get-NsxFirewallSection -Name $fs | New-NsxFirewallRule -Name $dfwany -Destination $sgn -Action allow -AppliedTo $sgn -EnableLogging -tag $catch -Position Bottom -Disabled