Powershell add tag to device #10012
-
Hi, does anyone have the powerhell code for adding a new tag to a device/virtual machine (with existing tags already assigned)? Tried variants of $UpdateVMJSON = $updateVM|ConvertTo-Json But not able to add a tag |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
IIRC when PATCHing new list of tags it should just be the ID numbers, so you'll need to extract the id numbers from the existing list to add the new entry
was GET result:
{ result:
tags: [
{ id: 1
name: foo
},
{ id: 2
name: bar
}
]
}
to add 3 it should be PATCH:
{ tags: [1,2,3] }
—
Mark Tinberg ***@***.***>
Division of Information Technology-Network Services
University of Wisconsin-Madison
…________________________________
From: AndreasMoe ***@***.***>
Sent: Monday, August 15, 2022 2:31 AM
To: netbox-community/netbox ***@***.***>
Cc: Subscribed ***@***.***>
Subject: [netbox-community/netbox] Powershell add tag to device (Discussion #10012)
Hi, does anyone have the powerhell code for adding a new tag to a device/virtual machine (with existing tags already assigned)?
Tried variants of
$Mytag = Invoke-RestMethod -Uri "https://xxx/api/extras/tags/?name=MytagName" -Headers $headersNetbox #single tag found
$FindDevice = Invoke-RestMethod -Uri "https://xxx/virtualization/virtual-machines/123/" -Headers $headersNetbox #single vm found
$updateVM=@{}
$updateVM["tags"]+=$Mytag.results # tried also {$Mytag},{$mytag.results}
$UpdateVMJSON = $updateVM|ConvertTo-Json
$UpdateDevice = Invoke-RestMethod -Uri "https://xxx/virtualization/virtual-machines/$($finddevice.results.id)/" -Headers $headersNetbox -Method Patch -Body $UpdateVMJSON
But not able to add a tag
—
Reply to this email directly, view it on GitHub<#10012>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/AAS7UM3COJHOCGLSJSH3EFDVZHW43ANCNFSM56RLPSLQ>.
You are receiving this because you are subscribed to this thread.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
Found a way to add tags and preserve old tags:
3.Find VM and check if existing tags contains wanted tag. If not add |
Beta Was this translation helpful? Give feedback.
Found a way to add tags and preserve old tags:
$VirtualMachinesPath = "/virtualization/virtual-machines/"
$BaseURI = "YOUR API URL without trailing /"
$MyTag ="Production"
$TagID = (Invoke-RestMethod -Uri "https://$($BaseUrl)/api/extras/tags/?name=$MyTag" -Headers $headers).results.id
3.Find VM and check if existing tags contains wanted tag. If not add
$ResponseVM = Invoke-RESTMethod -Method GET -Headers $Headers -URI "$($URIBase)$($VirtualMachinesPath)cf_vmid=$($VM.VMId)"
#placeholder for updates and tags
$VMInfo = @{}
$Tags = @()
#prefill wanted tag
$Tags+= $TagID
# Check if already tagged with wanted tag. If not, update $VMInfo (keeping other tags that mi…