Skip to content

Instantly share code, notes, and snippets.

@illuzian
Created September 23, 2020 04:43
Show Gist options
  • Select an option

  • Save illuzian/c1642e4fc42d44f93047f25f6b55523d to your computer and use it in GitHub Desktop.

Select an option

Save illuzian/c1642e4fc42d44f93047f25f6b55523d to your computer and use it in GitHub Desktop.
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import GenericResource
from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_exceptions import CloudError
vm_list = []
with open('vms.csv', 'r') as f:
for line in f.readlines():
vm_list.append(line.strip().lower())
new_tags = {"Tag": "Value"}
tenant_id = ''
client = ''
key = ''
api_version = '2019-09-01'
credentials = ServicePrincipalCredentials(
client_id=client,
secret=key,
tenant=tenant_id
)
subscription_client = SubscriptionClient(credentials)
for s in subscription_client.subscriptions.list():
resource_man_client = ResourceManagementClient(credentials, s.subscription_id)
for r in resource_man_client.resource_groups.list():
compute_man_client = ComputeManagementClient(credentials, s.subscription_id)
for vm in compute_man_client.virtual_machines.list(r.name):
if vm.name in vm_list:
set_tags = vm.tags
for k, v in new_tags.items():
set_tags[k] = v
try:
compute_man_client.virtual_machines.update(r.name, vm.name,
parameters=GenericResource(tags=set_tags))
except CloudError:
print("Failed to add tag to " + vm.name)
print("Added tags to " + vm.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment