Skip to content

Instantly share code, notes, and snippets.

@blndev
Last active August 21, 2017 20:03
Show Gist options
  • Save blndev/a9fb41706f41c25be80473c943bc2084 to your computer and use it in GitHub Desktop.
Save blndev/a9fb41706f41c25be80473c943bc2084 to your computer and use it in GitHub Desktop.
List all VMs in a Subscription of the German Azure Cloud
#!/usr/bin/env python
# requirements: pip install azure msrestazure
import os
'''
AZURE_PUBLIC_CLOUD
AZURE_CHINA_CLOUD
AZURE_US_GOV_CLOUD
AZURE_GERMAN_CLOUD
'''
from msrestazure.azure_cloud import AZURE_GERMAN_CLOUD as cloud_environment
from msrestazure.azure_active_directory import UserPassCredentials
from msrestazure.azure_active_directory import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
# Prefered way for Azure connection is the use of ServicePrincipalCredentials
# in environment variables. When they are not existing, then we ask for
# username and password
if os.environ.has_key("AZURE_CLIENT_ID"):
credentials = ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID'],
cloud_environment=cloud_environment
)
else:
credentials = UserPassCredentials(
username=raw_input('Username: '),
password=raw_input('Password: '),
tenant=raw_input('Tenant (AD Identifier): '),
cloud_environment=cloud_environment
)
if os.environ.has_key("AZURE_SUBSCRIPTION_ID"):
subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID')
else:
subscription_id = raw_input('Subscription (ID): ')
client = ResourceManagementClient(
credentials,
subscription_id,
base_url=cloud_environment.endpoints.resource_manager
)
compute_client = ComputeManagementClient(
credentials,
subscription_id,
base_url=cloud_environment.endpoints.resource_manager
)
try:
# List VMs in subscription
print('\nList VMs in subscription')
for vm in compute_client.virtual_machines.list_all():
print("\tVM: {}".format(vm.name))
pass
except Exception as e:
print e
raise
finally:
print ('done')
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment