Exploring Tags and PowerCLI
Tags were added to vSphere back in version 5.1 so they’re not a new feature but are still often overlooked. One or more tags can be applied to items (entities) in the inventory and then used as a search term or metadata not only in the GUI but also through tools such as PowerCLI. This post covers a few useful cmdlets for working with tags.
CmdLets
There are a number of cmdlets which deal with tags, here’s a quick list using Get-Command.
Notice that there’s three Nouns used here- “Tag” represents the tag itself. “TagAssignment” represents a relationship between a tag and another object (for example “This VM has been assigned This (or These) tags). Finally there’s “TagCategory” which represents the category that a tag belongs to.
Getting Tags
So, what can we do with tags in PowerCLI? Well, first we can look at a list of all the tags using Get-Tag. This returns a lot of information, particularly if you have assigned tags already, so we can neaten the quick view using the PowerShell “Select” function to show just the tag name and description:
1Get-Tag | Select Name, Description
2
3Name Description
4-- ------
5UrlShortener URL Shortener Service
6Documents Document Management Service
7Change Change Management Service
In this example, I’ve created three tags to represent three different services operating in my environment. We can carry on from here and find out which entities have been assigned the “Documents” tag- i.e. what VMs form the Document Management Service.
1(Get-TagAssignment |
2Where {$_.Tag.Name -eq 'Documents'}).Entity
3
4
5Name PowerState Num CPUs MemoryGB
6-- ------- ------ ------
7DocuWebServ PoweredOn 1 4.000
8DocuDBServ PoweredOn 2 16.000
9DocuFileServ PoweredOn 1 4.000
Or we could flip that and ask the question- “What tags does this VM have assigned?”
1Get-VM "DocuWebServ" |
2 Get-TagAssignment | Select Tag
3
4
5Tag
6---
7Documents
8WebServers
Getting Bigger
As we’re using PowerCLI we can join more and more functions together and make bigger and bigger queries. For example, we can list all VMs with their tags in a table.
1Select Name,@{Name="Tags";Expression={(Get-TagAssignment -Entity $_).Tag.Name}} |
2Where {$_.Tags} |
3Format-Table - Autosize
4
5Name Tags
6---- ---
7DocuWebServ {Documents, WebServers}
8DocuDBServ Documents
9DocuFileServ Documents
10URLShort1 {UrlShortener, WebServers}
11URLShort2 {UrlShortener, WebServers, TestAndDev}
This is only scratching the surface of the possibilities- by having useful metadata that lives with the VM and can be accessed programmatically we have plenty of avenues to explore in automation and reporting.