Skip to content

Instantly share code, notes, and snippets.

@Zsoldier
Last active June 27, 2024 22:42
Show Gist options
  • Select an option

  • Save Zsoldier/1a42161e53e841e2e3f3d1e02bd159c4 to your computer and use it in GitHub Desktop.

Select an option

Save Zsoldier/1a42161e53e841e2e3f3d1e02bd159c4 to your computer and use it in GitHub Desktop.
NSX-T 3.x+ VM/Virtual Machine Tag Management
#Requires -Module vmware.powercli
$VCCredential = Get-Credential
$NSXCredential = Get-Credential
$skipcertcheck = $true
$AuthMethod = “Basic"
$VCServer="0.0.0.0"
$NSXMgr=”0.0.0.0”
$apiendpoint = "/api/v1/fabric"
$base_url = ("https://" + $NSXMgr + $apiendpoint)
$tag = "Naka"
$scope = "NakaScope" # If scope not required, simply define as $null or ""
$vmnamefilter = "nakabuntu" # Not required. Will loop through all VM's otherwise.
Connect-VIServer $VCServer -Credential $VCCredential
$vms = Get-VM $vmnamefilter | Get-View -Property "Config"
# Add Tags to existing tags (Valid for NSX-T 3.1.2, previous versions only have update_tag)
$endpoint = "/virtual-machines"
$action = "add_tags"
Foreach ($vm in $vms)
{
$vmid = $vm.Config.InstanceUuid
If ([string]::IsNullOrWhiteSpace($Scope)){
$JSON = "
{
`"external_id`":`"$vmid`",
`"tags`": [
{
`"tag`":`"$Tag`"
}
]
}
"
}
Else{
$JSON = "
{
`"external_id`":`"$vmid`",
`"tags`": [
{
`"scope`":`"$scope`",
`"tag`":`"$Tag`"
}
]
}
"
}
$Data = Invoke-restmethod -Uri ($base_url + $EndPoint + "?action=" + $action) -Method POST -Body $JSON -ContentType 'application/json' -Credential $NSXCredential -SkipCertificateCheck:$skipcertcheck -Authentication:$AuthMethod
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment