Azure SDK For Python
Azure SDK For Python
Azure SDK For Python
Microsoft
1 Example Usage 3
2 Installation 5
2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 The azure meta-package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 Features 7
3.1 Azure Resource Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Azure Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Azure Service Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4 System Requirements: 11
5 Need Help?: 13
i
7.20 DNS Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
7.21 IoTHub Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
7.22 KeyVault Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
7.23 Managed Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
7.24 Standalone Managed Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
7.25 Virtual Machine with Managed Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
7.26 Virtual Machine Scale Sets with Managed Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
7.27 Other Operations with Managed Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
7.28 PowerBI Embedded Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
7.29 ServerManager Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
7.30 SQL Database Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
7.31 Traffic Manager Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
7.32 Service Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
7.33 Batch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
7.34 Azure Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
7.35 KeyVault . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.36 Azure Active Directory Graph Rbac API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
7.37 Service Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
7.38 azure.common package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.39 azure.batch package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.40 azure.graphrbac package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.41 azure.keyvault package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.42 azure.mgmt.authorization package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.43 azure.mgmt.batch package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.44 azure.mgmt.cdn package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.45 azure.mgmt.cognitiveservices package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.46 azure.mgmt.commerce package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
7.47 azure.mgmt.compute.compute package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
7.48 azure.mgmt.compute.containerservice package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
7.49 azure.mgmt.containerregistry package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.50 azure.mgmt.datalake.analytics.account package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.51 azure.mgmt.datalake.analytics.catalog package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.52 azure.mgmt.datalake.analytics.job package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.53 azure.mgmt.datalake.store package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.54 azure.mgmt.devtestlabs package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.55 azure.mgmt.dns package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.56 azure.mgmt.documentdb package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.57 azure.mgmt.eventhub package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
7.58 azure.mgmt.iothub package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
7.59 azure.mgmt.keyvault package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
7.60 azure.mgmt.logic package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
7.61 azure.mgmt.media package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.62 azure.mgmt.monitor package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.63 azure.mgmt.network package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
7.64 azure.mgmt.notificationhubs package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.65 azure.mgmt.powerbiembedded package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7.66 azure.mgmt.redis package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.67 azure.mgmt.resource.features package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.68 azure.mgmt.resource.links package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.69 azure.mgmt.resource.locks package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.70 azure.mgmt.resource.policy package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
7.71 azure.mgmt.resource.resources package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.72 azure.mgmt.resource.subscriptions package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.73 azure.mgmt.scheduler package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
ii
7.74 azure.mgmt.search package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.75 azure.mgmt.servermanager package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.76 azure.mgmt.servicebus package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.77 azure.mgmt.sql package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.78 azure.mgmt.storage package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.79 azure.mgmt.trafficmanager package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.80 azure.mgmt.web package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.81 azure.monitor package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.82 azure.servicebus package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.83 azure.servicemanagement package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
iii
iv
Azure SDK for Python Documentation, Release 2.0.0 RC6
The Azure SDK for Python is a set of libraries which allow you to work on Azure for your management, runtime or
data needs.
For a more general view of Azure and Python, you can go on the Python Developer Center for Azure
User Documentation 1
Azure SDK for Python Documentation, Release 2.0.0 RC6
2 User Documentation
CHAPTER 1
Example Usage
resource_group_name = 'my_resource_group'
storage_account_name = 'myuniquestorageaccount'
resource_client.resource_groups.create_or_update(
resource_group_name,
{
'location':'westus'
}
)
async_create = storage_client.storage_accounts.create(
resource_group_name,
storage_account_name,
{
'location':'westus',
'kind':'storage',
3
Azure SDK for Python Documentation, Release 2.0.0 RC6
'sku': {
'name':'standard_ragrs'
}
}
)
async_create.wait()
blob_service.create_container(
'mycontainername',
public_access=PublicAccess.Blob
)
blob_service.create_blob_from_bytes(
'mycontainername',
'myblobname',
b'<center><h1>Hello World!</h1></center>',
content_settings=ContentSettings('text/html')
)
print(blob_service.make_blob_url('mycontainername', 'myblobname'))
Installation
Overview
You can install individually each library for each Azure service:
$ pip install --pre azure-mgmt-compute # will install only the latest Compute
˓→Management library
More details and information about the available libraries and their status can be found in the Installation Page
You can also install a set of Azure libraries in a single line using the azure meta-package. Since not all packages
in this meta-package are published as stable yet, the azure meta-package is still in preview. However, the core
packages, from code quality/completeness perspectives can at this time be considered “stable” - it will be officially
labeled as such in sync with other languages as soon as possible. We are not planning on any further major changes
until then.
Since it’s a preview release, you need to use the --pre flag:
or directly
5
Azure SDK for Python Documentation, Release 2.0.0 RC6
Important: The azure meta-package 1.0.3 is deprecated and is not working anymore.
6 Chapter 2. Installation
CHAPTER 3
Features
All documentation of management libraries for Azure are on this website. This includes:
• Authorization : Permissions, roles and more
• Batch : Manage Batch accounts and applications
• Content Delivery Network : Profiles, endpoints creation and more
• Cognitive Services : Create CS accounts and more
• Commerce - Billing API : RateCard and Usage Billing API
• Compute : Create virtual machines and more
• Data Lake Analytics : Manage account, job, catalog and more
• Data Lake Store : Manage account and more
• DevTestLabs : Create labs and more
• DNS : Create DNS zone, record set and more
• IoTHub : Create IoTHub account and more
• KeyVault : Create vaults and more
• App Service : Create App plan, Web Apps, Logic Apps and more
• Media Services : Create account and more
• Network : Create virtual networks, network interfaces, public IPs and more
• Notification Hubs : Namespaces, hub creation/deletion and more
• PowerBI Embedded : Create account and more
• Redis Cache : Create cache and more
• Resource Management:
7
Azure SDK for Python Documentation, Release 2.0.0 RC6
Azure Runtime
Note: For critical performance issue, the Service Bus team currently recommends AMQP.
These Azure services have Python data libraries which are directly hosted by the service team or are extensively
documented on the Azure documentation website:
• Storage
• Azure Data Lake Store Filesystem
• Azure IoT Hub service and device SDKs for Python
• SQL Azure
• DocumentDB
• Application Insight
• Redis Cache
• Write an Azure WebApp in Python
Note: The Service Management SDK is deprecated and no more features will be added.
This page describes the usage and detailed features of Azure Service Management SDK. At a glance:
8 Chapter 3. Features
Azure SDK for Python Documentation, Release 2.0.0 RC6
10 Chapter 3. Features
CHAPTER 4
System Requirements:
The supported Python versions are 2.7.x, 3.3.x, 3.4.x, 3.5.x and 3.6.x To download Python, please visit https://www.
python.org/download/
We recommend Python Tools for Visual Studio as a development environment for developing your applications. Please
visit http://aka.ms/python for more information.
11
Azure SDK for Python Documentation, Release 2.0.0 RC6
Need Help?:
Be sure to check out the Microsoft Azure Developer Forums on Stack Overflow if you have trouble with the provided
code.
13
Azure SDK for Python Documentation, Release 2.0.0 RC6
If you would like to become an active contributor to this project please follow the instructions provided in Microsoft
Azure Projects Contribution Guidelines.
If you encounter any bugs with the library please file an issue in the Issues section of the project.
15
Azure SDK for Python Documentation, Release 2.0.0 RC6
• genindex
• modindex
• search
Installation
You can install individually each library for each Azure service:
$ pip install --pre azure-mgmt-compute # will install only the latest Compute
˓→Management library
You can also install a set of Azure libraries in a single line using the azure meta-package. Since not all packages
in this meta-package are published as stable yet, the azure meta-package is still in preview. However, the core
packages, from code quality/completeness perspectives can at this time be considered “stable” - it will be officially
labeled as such in sync with other languages as soon as possible. We are not planning on any further major changes
until then.
Since it’s a preview release, you need to use the --pre flag:
or directly
17
Azure SDK for Python Documentation, Release 2.0.0 RC6
Important: The azure meta-package 1.0.3 is deprecated and is not working anymore.
Available packages
Stable packages
Preview packages
And use it as credentials in your management configuration client. These three instances correspond to:
• OAuth authentication using Azure Active Directory user/password
• OAuth authentication using Active Directory application and service principal
• A wrapper on top of ADAL for Python <https://github.com/AzureAD/azure-activedirectory-library-for-python>
credentials = ServicePrincipalCredentials(
client_id = 'ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF',
secret = 'XXXXXXXXXXXXXXXXXXXXXXXX',
tenant = 'ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF'
)
Using AD User/Password
credentials = UserPassCredentials(
'[email protected]', # Your new user
'my_smart_password', # Your password
)
Using ADAL
ADAL for Python is a library from the Azure Active Directory team, that proposes the more complex scenarios not
covered by the two previous instances (like 2FA). Please refer to the ADAL website for all the available scenarios list
and samples.
For example, this code from the ADAL tutorial:
context = adal.AuthenticationContext('https://login.microsoftonline.com/ABCDEFGH-1234-
˓→1234-1234-ABCDEFGHIJKL')
context = adal.AuthenticationContext('https://login.microsoftonline.com/ABCDEFGH-1234-
˓→1234-1234-ABCDEFGHIJKL')
context = adal.AuthenticationContext('https://login.microsoftonline.com/ABCDEFGH-1234-
˓→1234-1234-ABCDEFGHIJKL')
Note that the UserPassCredentials and ServicePrincipalCredentials scenarios are also covered by the ADAL library.
In the near future their implementation will be rewritten using ADAL.
You can use the Azure SDK for Python to connect to all regions where Azure is available (list of Azure regions is
available here).
By default, the Azure SDK for Python is configured to connect to public Azure. To connect to another region, a few
things have to be considered:
• What is the endpoint where to ask for a token (authentication)?
• What is the endpoint where I will use this token (usage)?
This is a generic example:
credentials = UserPassCredentials(
'[email protected]',
'my_smart_password',
auth_uri=authentication_endpoint,
resource=azure_endpoint
)
subscription_id = '33333333-3333-3333-3333-333333333333'
resource_client = ResourceManagementClient(
credentials,
subscription_id,
base_url=azure_endpoint
)
Azure Government
Azure Government is currently using the same authentication endpoint that public azure. This means that we can use
the default authentication_endpoint.
azure_endpoint = 'https://management.usgovcloudapi.net/'
credentials = UserPassCredentials(
'[email protected]',
'my_smart_password',
resource=azure_endpoint
)
subscription_id = '33333333-3333-3333-3333-333333333333'
resource_client = ResourceManagementClient(
credentials,
subscription_id,
base_url=azure_endpoint
)
Azure Germany
authentication_endpoint = 'https://login.microsoftonline.de/'
azure_endpoint = 'https://management.microsoftazure.de/'
credentials = UserPassCredentials(
'[email protected]',
'my_smart_password',
auth_uri=authentication_endpoint,
resource=azure_endpoint
)
subscription_id = '33333333-3333-3333-3333-333333333333'
resource_client = ResourceManagementClient(
credentials,
subscription_id,
base_url=azure_endpoint
)
Azure China
authentication_endpoint = 'https://login.chinacloudapi.cn/'
azure_endpoint = 'https://management.chinacloudapi.cn/'
credentials = UserPassCredentials(
'[email protected]',
'my_smart_password',
auth_uri=authentication_endpoint,
resource=azure_endpoint
)
subscription_id = '33333333-3333-3333-3333-333333333333'
resource_client = ResourceManagementClient(
credentials,
subscription_id,
base_url=azure_endpoint
)
Exception handling
Important: This document concerns every package except azure-servicebus and azure-servicemanagement-legacy
This document covers the exceptions that you can get from the Azure SDK for Python, and will help you decide what
is worth retrying or what is a critical failure, depending on your application.
Every exception related to the service content will be referenced in the docstring of the method. For instance, for this
create_or_update operation you can see that you might receive a CloudError.
Where the service team provides no specific sub-classing, the basic exception you can expect from an operation is
CloudError. In some situations however, the exceptions are specialized by package (see azure-batch package
which uses BatchErrorException). If a specialized exception is used, it will always be a sub-class at some level
of ClientException.
Whether you should retry the same query or not for these exceptions depends on the service and the error content and
cannot be generalized on this article. For instance, an update to a SQL Database might be refused because you have
another underlying operation (in this case you can retry); or a create request can be refused because your selected
name does not meet the pattern enforced by the server (in this case retry will never work). Use the error and response
attributes of CloudError to decide.
All these operations can also raise this set of generic exceptions that are defined in the msrest.exceptions
module:
• AuthenticationError: password invalid/expired, etc. Retry will likely not work.
• ClientRequestError: requests library raised an exception (connection error, mostly HTTP level issues).
Retry may work, though unlikely if your base_url is incorrect.
• DeserializationError: unexpected RestAPI answer. Retry will likely not work. Please create an issue
on Github if you see this exception.
• HttpOperationError: bad HTTP status code from Azure. See inner exception to decide if it’s worth
retrying.
• SerializationError: unable to serialize your request. Your Python code didn’t respect the expected
model. Retry will never work. Please create an issue on Github if you see this exception and are 100% your
parameters are correct.
• TokenExpiredError: please renew your credentials. Likely retry with new credentials will be ok.
• ValidationError: client side check of your request failed. Fix your parameters with expected value. For
instance, you didn’t respect the regexp for the account name. This will never work on retry.
Asynchronous operation
async_poller = client.network_security_groups.create_or_update(myparameters)
result = async_poller.result()
async_poller = client.network_security_groups.create_or_update(myparameters)
async_poller.wait()
Our recommendation is to surround both of the statements with the necessary try/except. More precisely, the first call
might fail on the initial call and the second one might fail during polling the status of the operation
Important: Old versions of the packages never failed on the first call, but this behavior was replaced by the one
described and you should follow this pattern even for old packages.
Raw operation
All operations accept a raw=True parameter to indicate that the method must return the requests.Response instance
directly. All the above exceptions are still applicable, except for DeserializationError, since the response will
not be deserialized in this case.
Resource Management
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
https://github.com/Azure-Samples/resource-manager-python-resources-and-groups
https://github.com/Azure-Samples/resource-manager-python-template-deployment
logic_client = LogicManagementClient(
credentials,
subscription_id
)
web_client = WebSiteManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Web')
resource_client.providers.register('Microsoft.Logic')
https://github.com/Azure-Samples/app-service-web-python-manage
group_name = 'myresourcegroup'
workflow_name = '12HourHeartBeat'
logic_client.workflows.create_or_update(
group_name,
workflow_name,
Workflow(
location = 'West US',
definition={
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/
˓→schemas/2016-06-01/workflowdefinition.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"triggers": {},
"actions": {},
"outputs": {}
}
)
)
Authorization Management
authorization_client = AuthorizationManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Authorization')
The following code checks permissions in a given resource group. To create or manage resource groups, see Resource
Management.
group_name = 'myresourcegroup'
permissions = self.authorization_client.permissions.list_for_resource_group(
group_name
)
# permissions is a iterable of Permissions instances
Batch Management
For more information on the Azure Batch service, check out the Batch Documentation. For working samples, see the
Batch samples repo.
The API documentation: API
The following code creates an instance of the management client. You will need to provide your subscription_id
which can be retrieved from your subscription list.
See Resource Management Authentication for details on handling Azure Active Directory authentication with the
Python SDK, and creating a Credentials instance.
subscription_id = '33333333-3333-3333-3333-333333333333'
batch_client = BatchManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Batch')
A Batch Account will need to be created in a specified location and resource group. The default Batch Account quota
is 1 per location per subscription, but can be increased to a maximum of 50. Please contact support if you require a
quota increase. For more information on resource groups and resource management, see Resource Management.
In order to make use of Application Packages, a storage account will need to be linked to the Batch Account. A linked
storage account is known as ‘auto-storage’. A storage account can be created with the Storage Resource Management
Client.
RESOURCE_GROUP = 'python_sdk'
LOCATION = 'westus'
resource_client = = azure.mgmt.storage.ResourceManagementClient(
azure.mgmt.resources.ResourceManagementClientConfiguration(
credentials, # See section above
subscription_id
)
)
group = azure.mgmt.resource.resources.models.ResourceGroup(
name=RESOURCE_GROUP,
location=LOCATION
)
resource_client.resource_groups.create_or_update(
RESOURCE_GROUP,
group,
)
subscription_id,
RESOURCE_GROUP,
'pythonstorageaccount'
)
batch_account = azure.mgmt.batch.models.BatchAccountCreateParameters(
location=LOCATION,
auto_storage=azure.mgmt.batch.models.AutoStorageBaseProperties(storage_
˓→resource)
)
creating = batch_client.account.create('MyBatchAccount', LOCATION, batch_account)
creating.wait()
Account keys (used for authenticating the Batch Client) can be retrieved or regenerated.
batch_client.account.regenerate_key(
RESOURCE_GROUP,
'MyBatchAccount',
'Primary'
)
accounts_keys = batch_client.account.list_keys(RESOURCE_GROUP, 'MyBatchAccount')
print('Updated primary key: {}'.format(accounts_keys.primary))
Application Packages
Application packages can be configured to be used by the the Batch Client for running tasks. An Application can
have multiple versioned packages (zipped directories containing the application to be executed on the Compute Node)
associated with it. You can find an overview of this feature in this article on application deployment with Azure Batch
Applications.
cdn_client = CdnManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Cdn')
output = cdn_client.check_name_availability('myendpoint')
# output is a CheckNameAvailabilityOutput instance
print(output.name_available)
commerce_client = UsageManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Commerce')
# OfferDurableID: https://azure.microsoft.com/en-us/support/legal/offer-details/
rate = commerce_client.rate_card.get(
"OfferDurableId eq 'MS-AZR-0062P' and Currency eq 'USD' and Locale eq 'en-US' and
˓→RegionInfo eq 'US'"
Get Usage
compute_client = ComputeManagementClient(
credentials,
subscription_id
)
network_client = NetworkManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the compute/network ARM APIs require a one-time registration of the storage provider with your
subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Compute')
resource_client.providers.register('Microsoft.Network')
You can get a fully functionnal Virtual Machine sample from the AzureSample Github repository: https://github.com/
Azure-Samples/virtual-machines-python-manage
You can get a fully functionnal Load Balancer sample from the AzureSample Github repository: https://github.com/
Azure-Samples/network-python-manage-loadbalancer
List images
Use the following code to print all of the available images to use for creating virtual machines, including all skus and
versions.
region = 'eastus2'
result_list_pub = compute_client.virtual_machine_images.list_publishers(
region,
)
You will need to provide your subscription_id which can be retrieved from your subscription list.
See Resource Management Authentication for details on handling Azure Active Directory authentication with the
Python SDK, and creating a Credentials instance.
from azure.mgmt.notificationhubs import NotificationHubsManagementClient
from azure.common.credentials import UserPassCredentials
redis_client = NotificationHubsManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
from azure.mgmt.resource.resources import ResourceManagementClient
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.NotificationHubs')
account_name = 'mynotificationhub'
output = notificationhubs_client.namespaces.check_availability(
azure.mgmt.notificationhubs.models.CheckAvailabilityParameters(
name = account_name
)
)
# output is a CheckAvailibilityResource instance
print(output.is_availiable) # Yes, it's 'availiable', it's a typo in the REST API
redis_client = RedisManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Cache')
The following code creates a new redis cache under an existing resource group. To create or manage resource groups,
see Resource Management.
group_name = 'myresourcegroup'
cache_name = 'mycachename'
redis_cache = redis_client.redis.create_or_update(
group_name,
cache_name,
RedisCreateOrUpdateParameters(
sku = Sku(name = 'Basic', family = 'C', capacity = '1'),
location = "West US"
)
)
# redis_cache is a RedisResourceWithAccessKey instance
Scheduler Management
scheduler_client = SchedulerManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the storage ARM APIs require a one-time registration of the storage provider with your subscrip-
tion.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Scheduler')
The following code creates a job collection under an existing resource group. To create or manage resource groups,
see Resource Management.
group_name = 'myresourcegroup'
job_collection_name = "myjobcollection"
scheduler_client.job_collections.create_or_update(
group_name,
job_collection_name,
JobCollectionDefinition(
location = "West US",
properties = JobCollectionProperties(
sku = Sku(
name="Free"
)
)
)
)
# scheduler_client is a JobCollectionDefinition instance
Storage Management
storage_client = StorageManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the storage ARM APIs require a one-time registration of the storage provider with your subscrip-
tion.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
from azure.mgmt.resource.resources import ResourceManagementClient
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Storage')
Usage sample
https://github.com/Azure-Samples/storage-python-manage
cognitiveservices_client = CognitiveServicesManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
from azure.mgmt.resource.resources import ResourceManagementClient
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.CognitiveServices')
account_client = DataLakeAnalyticsAccountManagementClient(
credentials,
subscription_id
)
catalog_client = DataLakeAnalyticsCatalogManagementClient(
credentials,
subscription_id
)
job_client = DataLakeAnalyticsJobManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.DataLakeAnalytics')
Samples
Samples writing in progress! In the meantime, you should look at the unit tests of this package:
https://github.com/Azure/azure-sdk-for-python/blob/master/azure-mgmt/tests/test_mgmt_datalake_analytics.py
client = DataLakeStoreAccountManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.DataLakeStore')
Samples
Samples writing in progress! In the meantime, you should look at the unit tests of this package:
https://github.com/Azure/azure-sdk-for-python/blob/master/azure-mgmt/tests/test_mgmt_datalake_store.py
DevTestLabs Management
devtestlabs_client = DevTestLabsClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.DevTestLab')
Create lab
async_lab = self.client.lab.create_or_update_resource(
'MyResourceGroup',
'MyLab',
{'location': 'westus'}
)
lab = async_lab.result() # Blocking wait
DNS Management
dns_client = DnsManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Network')
zone = dns_client.zones.create_or_update(
'MyResourceGroup',
'pydns.com',
{
'location': 'global'
}
)
record_set = dns_client.record_sets.create_or_update(
'MyResourceGroup',
'pydns.com',
'MyRecordSet',
'A',
{
"ttl": 300,
"arecords": [
{
"ipv4_address": "1.2.3.4"
},
{
"ipv4_address": "1.2.3.5"
}
]
}
)
IoTHub Management
You will need to provide your subscription_id which can be retrieved from your subscription list.
See Resource Management Authentication for details on handling Azure Active Directory authentication with the
Python SDK, and creating a Credentials instance.
from azure.mgmt.iothub import IotHubClient
from azure.common.credentials import UserPassCredentials
iothub_client = IotHubClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
from azure.mgmt.resource.resources import ResourceManagementClient
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Devices')
Create an IoTHub
async_iot_hub = iothub_client.iot_hub_resource.create_or_update(
'MyResourceGroup',
'MyIoTHubAccount',
{
'location': 'westus',
'subscriptionid': subscription_id,
'resourcegroup': 'MyResourceGroup',
'sku': {
'name': 'S1',
'capacity': 2
},
'properties': {
'enable_file_upload_notifications': False,
'operations_monitoring_properties': {
'events': {
"C2DCommands": "Error",
"DeviceTelemetry": "Error",
"DeviceIdentityOperations": "Error",
"Connections": "Information"
}
},
"features": "None",
}
}
)
iothub = async_iot_hub.result() # Blocking wait for creation
KeyVault Management
kv_client = KeyVaultManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.KeyVault')
Samples usage
https://github.com/Azure-Samples/key-vault-python-manage
Managed Disks
Azure Managed Disks and 1000 VMs in a Scale Set are now generally available. Azure Managed Disks provide
a simplified disk Management, enhanced Scalability, better Security and Scale. It takes away the notion of storage
account for disks, enabling customers to scale without worrying about the limitations associated with storage accounts.
This post provides a quick introduction and reference on consuming the service from Python.
From a developer perspective, the Managed Disks experience in Azure CLI is idomatic to the CLI experience in other
cross-platform tools. You can use the Azure Python SDK and the azure-mgmt-compute package 0.33.0 to administer
Managed Disks. You can create a compute client using this tutorial. The complete API documentation is available on
ReadTheDocs.
async_creation = compute_client.disks.create_or_update(
'my_resource_group',
'my_disk_name',
{
'location': 'westus',
'disk_size_gb': 20,
'creation_data': {
'create_option': DiskCreateOption.empty
}
}
)
disk_resource = async_creation.result()
async_creation = compute_client.disks.create_or_update(
'my_resource_group',
'my_disk_name',
{
'location': 'westus',
'creation_data': {
'create_option': DiskCreateOption.import_enum,
'source_uri': 'https://bg09.blob.core.windows.net/vm-images/non-existent.
˓→vhd'
}
}
)
disk_resource = async_creation.result()
disk_resource = async_creation.result()
You can create a Virtual Machine with an implicit Managed Disk for a specific disk image. Creation is simplified with
implicit creation of managed disks without specifying all the disk details. You do not have to worry about creating and
managing Storage Accounts.
A Managed Disk is created implicitly when creating VM from an OS image in Azure. In the storage_profile
parameter, os_disk is now optional and you don’t have to create a storage account as required precondition to create
a Virtual Machine.
storage_profile = azure.mgmt.compute.models.StorageProfile(
image_reference = azure.mgmt.compute.models.ImageReference(
publisher='Canonical',
offer='UbuntuServer',
sku='16.04-LTS',
version='latest'
)
)
This storage_profile parameter is now valid. To get a complete example on how to create a VM in Python
(including network, etc), check the full VM tutorial in Python here.
You can easily attach a previously provisioned Managed Disk.
vm = compute.virtual_machines.get(
'my_resource_group',
'my_vm'
)
managed_disk = compute_client.disks.get('my_resource_group', 'myDisk')
vm.storage_profile.data_disks.append({
'lun': 12, # You choose the value, depending of what is available for you
'name': managed_disk.name,
'create_option': DiskCreateOption.attach,
'managed_disk': {
'id': managed_disk.id
}
})
async_update = compute_client.virtual_machines.create_or_update(
'my_resource_group',
vm.name,
vm,
)
async_update.wait()
Before Managed Disks, you needed to create a storage account manually for all the VMs you wanted inside your
Scale Set, and then use the list parameter vhd_containers to provide all the storage account name to the Scale
Set RestAPI. The official transition guide is available in this article.
Now with Managed Disk, you don’t have to manage any storage account at all. If you’re are used to the VMSS Python
SDK, your storage_profile can now be exactly the same as the one used in VM creation:
'storage_profile': {
'image_reference': {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "16.04-LTS",
"version": "latest"
}
},
naming_infix = "PyTestInfix"
vmss_parameters = {
'location': self.region,
"overprovision": True,
"upgrade_policy": {
"mode": "Manual"
},
'sku': {
'name': 'Standard_A1',
'tier': 'Standard',
'capacity': 5
},
'virtual_machine_profile': {
'storage_profile': {
'image_reference': {
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "16.04-LTS",
"version": "latest"
}
},
'os_profile': {
'computer_name_prefix': naming_infix,
'admin_username': 'Foo12',
'admin_password': 'BaR@123!!!!',
},
'network_profile': {
'network_interface_configurations' : [{
'name': naming_infix + 'nic',
"primary": True,
'ip_configurations': [{
'name': naming_infix + 'ipconfig',
'subnet': {
'id': subnet.id
}
}]
}]
}
}
}
)
async_update.wait()
async_create_image = compute_client.images.create_or_update(
'my_resource_group',
'myImage',
{
'location': 'westus',
'storage_profile': {
'os_disk': {
'os_type': 'Linux',
'os_state': "Generalized",
'blob_uri': 'https://bg09.blob.core.windows.net/vm-images/non-
˓→existent.vhd',
'caching': "ReadWrite",
}
}
}
)
image = async_create_image.result()
pbi_client = PowerBIEmbeddedManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.PowerBI')
ServerManager Management
servermanager_client = ServerManagement(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.ServerManagement')
Create gateway
gateway_async = servermanager_client.gateway.create(
'MyResourceGroup',
'MyGateway',
'centralus'
)
gateway = gateway_async.result() # Blocking wait
credentials = UserPassCredentials(
'[email protected]', # Your user
'my_password', # Your password
)
sql_client = SqlManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Sql')
Servers/Databases sample
You can get a fully functional SQL servers/databases sample from the AzureSample Github repository: https://github.
com/Azure-Samples/sql-database-python-manage
tf_client = TrafficManagerManagementClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Network')
Service Management
Usage
Set-up certificates
You will need two certificates, one for the server (a .cer file) and one for the client (a .pem file).
You can download your Azure publish settings file and use the certificate that is embedded in that file to create the
client certificate. The server certificate already exists, so you won’t need to upload one.
To do this, download your publish settings then use this code to create the .pem file.
subscription_id = get_certificate_from_publish_settings(
publish_settings_path='MyAccount.PublishSettings',
path_to_write_certificate='mycert.pem',
subscription_id='00000000-0000-0000-0000-000000000000',
)
The subscription id parameter is optional. If there are more than one subscription in the publish settings, the first one
will be used.
openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
openssl x509 -inform pem -in mycert.pem -outform der -out mycert.cer
After you have created the certificate, you will need to upload the .cer file to Microsoft Azure via the “Upload” action
of the “Settings” tab of the management portal.
Initialization
To initialize the management service, pass in your subscription id and the path to the .pem file.
locations = sms.list_locations()
for location in locations:
print(location.name)
To create a storage service, you need a name for the service (between 3 and 24 lowercase characters and unique within
Microsoft Azure), a label (up to 100 characters, automatically encoded to base-64), and either a location or an affinity
group.
name = "mystorageservice"
desc = name
label = name
location = 'West US'
A cloud service is also known as a hosted service (from earlier versions of Microsoft Azure). The cre-
ate_hosted_service method allows you to create a new hosted service by providing a hosted service name (which
must be unique in Microsoft Azure), a label (automatically encoded to base-64), and the location or the affinity group
for your service.
name = "myhostedservice"
desc = name
label = name
location = 'West US'
Create a Deployment
To make a new deployment to Azure you must store the package file in a Microsoft Azure Blob Storage account under
the same subscription as the hosted service to which the package is being uploaded. You can create a deployment
package with the Microsoft Azure PowerShell cmdlets, or with the cspack commandline tool.
service_name = "myhostedservice"
deployment_name = "v1"
slot = 'Production'
package_url = "URL_for_.cspkg_file"
configuration = base64.b64encode(open(file_path, 'rb').read('path_to_.cscfg_file'))
label = service_name
result = sms.create_deployment(service_name,
slot,
deployment_name,
package_url,
label,
configuration)
operation = sms.get_operation_status(result.request_id)
print('Operation status: ' + operation.status)
Batch
For more information on the Azure Batch service, check out the Batch Documentation. For working samples, see the
Batch samples repo.
The following code creates an instance of the Batch client. The Batch client provides access to create pools, manage
and schedule jobs, and access compute nodes.
A Batch Account that allows the Batch Service to allocate pools can be authenticated either via Shared Key authen-
tication, or an Azure Active Directory token. Batch Accounts configured to allocate pools into the users subscription
must be authenticated with an Azure Active Directory token.
For more information on creating and managing Batch accounts, including retrieving account URL and keys, and pool
allocation modes, see the Batch Management Client.
credentials = ServicePrincipalCredentials(
client_id=CLIENT_ID,
secret=SECRET,
tenant=TENANT_ID,
resource="https://batch.core.windows.net/"
)
batch_client = BatchServiceClient(
credentials,
base_url=BATCH_ACCOUNT_URL
)
The Batch Client allows you to create, modify, and delete Batch Pools. You can find more information on pools in this
overview of Azure Batch features.
batch_client.pool.add(new_pool)
# Create a new pool with Linux nodes using Azure Virtual Machines
# Marketplace images. For full example, see the Batch samples repo.
pool = batch.models.PoolAddParameter(
id='my_pool',
enable_inter_node_communication=True,
virtual_machine_configuration=batch.models.VirtualMachineConfiguration(
image_reference=MY_IMAGE_REF,
node_agent_sku_id=MY_NODE_AGENT),
vm_size='small',
target_dedicated=6,
start_task=batch.models.StartTask(
command_line=STARTTASK_RESOURCE_FILE,
run_elevated=True,
wait_for_success=True,
resource_files=[
batch.models.ResourceFile(
file_path=STARTTASK_RESOURCE_FILE, blob_source=SAS_URL)
]),
)
batch_client.pool.add(new_pool)
Existing pools can be upgraded, patched, and resized. You can change the size of a pool either explicitly, or via an
auto-scaling formula. For more information, see this article on automatically scaling nodes in a Batch pool.
7.33. Batch 59
Azure SDK for Python Documentation, Release 2.0.0 RC6
# Update or patch a pool. Note that when updating, all pool parameters must be
˓→updated,
# Upgrade pool OS
batch_client.pool.upgrade_os('my_pool', 'WA-GUEST-OS-4.28_201601-01')
You can monitor pools by retrieving data individually, or grouped using OData filters. You can learn more about filters
with this article on querying the Batch service efficiently. You can also retrieve statistics on the usage of a specific
pool, or all the pools in the lifetime of your Batch account.
if batch_client.pool.exists('my_pool'):
my_pool = batch_client.pool.get('my_pool')
print("Current state: {}".format(my_pool.allocation_state))
stats = batch_client.pool.get_all_pools_lifetime_statistics()
print("Average CPU usage across pools: {}%".format(stats.resource_stats.avg_cpu_
˓→percentage))
The Batch client also allows you to access individual nodes within a pool.
# List compute nodes in a pool, then remove any erroring ones
nodes = list(batch_client.compute_node.list())
errored = [n.id for n in nodes if n.state == batch.models.ComputeNodeState.unusable]
working_nodes = [n.id for n in nodes if n not in errored]
batch_client.pool.remove_nodes('my_pool', batch.models.NodeRemoveParameter(errored))
# Add a user account to a Windows Cloud Services node and retrieve an RDP file
user = batch.models.ComputeNodeUser('MyTestUser', password='kt#_gahr!@aGERDXA')
batch_client.compute_node.add_user('my_pool', working_nodes[0], user)
with open('node.rdp', 'w') as rdp_file:
data = batch_client.compute_node.get_remote_desktop('my_pool', working_
˓→nodes[0])
You can create new jobs and add tasks, monitor existing jobs and download outputs. You can also set up job schedules
for future or recurring jobs.
# Create Job
job = batch.models.JobAddParameter(
'python_test_job',
batch.models.PoolInformation(pool_id='my_pool')
)
batch_client.job.add(job)
# Add a task
task = batch.models.TaskAddParameter(
'python_task_1',
'cmd /c echo hello world'
)
batch_client.task.add('python_test_job', task)
7.33. Batch 61
Azure SDK for Python Documentation, Release 2.0.0 RC6
'python_test_job',
'python_task_1',
'stdout.txt'
)
for data in output:
file_output.write(data)
Azure Monitor
client = MonitorClient(
credentials,
subscription_id
)
Registration
Some operations in the ARM APIs require a one-time registration of the provider with your subscription.
Use the following code to do the registration. You can use the same credentials you created in the previous section.
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Insights')
You also might need to add the “Monitoring Contributor Service Role” role to your credentials. See here to do it using
the Python CLI: https://docs.microsoft.com/cli/azure/role/assignment
This sample gets the logs from the ActivityLog of today for resource group ResourceGroupName, filtering the at-
tributes to get only the “eventName” and “operationName”.
A complete list of available keywords for filters and available attributes is available here: https://msdn.microsoft.com/
library/azure/dn931934.aspx
import datetime
today = datetime.datetime.now().date()
filter = " and ".join([
"eventTimestamp ge {}".format(today),
"resourceGroupName eq 'ResourceGroupName'"
])
select = ",".join([
"eventName",
"operationName"
])
activity_logs = client.activity_logs.list(
filter=filter,
select=select
)
for log in activity_logs:
# assert isinstance(log, azure.monitor.models.EventData)
print(" ".join([
log.event_name.localized_value,
log.operation_name.localized_value
]))
Metrics
import datetime
today = datetime.datetime.now().date()
yesterday = today - datetime.timedelta(days=1)
metrics_data = client.metrics.list(
resource_id,
filter=filter
)
# Example of result:
# Percentage CPU (percent)
# 2016-11-16 00:00:00+00:00: 72.0
# 2016-11-16 01:00:00+00:00: 90.59
KeyVault
Important: You must specify resource=”https://vault.azure.net” while authenticating to get a valid token
client = KeyVaultClient(
credentials
)
7.35. KeyVault 65
Azure SDK for Python Documentation, Release 2.0.0 RC6
Access policies
Some operations require the correct access policies for your credentials.
If you get an “Unauthorized” error, please add the correct access policies to this credentials using the Azure Portal,
the Azure CLI or the Key Vault Management SDK itself
Example
# Create a key
key_bundle = client.create_key(KEY_VAULT_URI, 'FirstKey', 'RSA')
key_id = key_vault_id.parse_key_id(key_bundle.key.kid)
# Delete a key
client.delete_key(KEY_VAULT_URI, 'FirstKey')
# Create a secret
secret_bundle = client.set_secret(KEY_VAULT_URI, 'FirstSecret', 'Hush, that is secret!
˓→!')
secret_id = key_vault_id.parse_secret_id(secret_bundle.id)
# Delete a secret
client.delete_secret(KEY_VAULT_URI, 'FirstSecret')
Note: You need to change the resource parameter to https://graph.windows.net while creating the credentials instance
tenant_id = "myad.onmicrosoft.com"
graphrbac_client = GraphRbacManagementClient(
credentials,
tenant_id
)
Manage users
The following code creates a user, get it directly and by list filtering, and then delete it. Filter syntax can be found
here.
user = graphrbac_client.user_operations.create(
UserCreateParameters(
user_principal_name="testbuddy@{}".format(MY_AD_DOMAIN),
account_enabled=False,
display_name='Test Buddy',
mail_nickname='testbuddy',
password_profile=UserCreateParametersPasswordProfile(
password='MyStr0ngP4ssword',
force_change_password_next_login=True
)
)
)
# user is a User instance
self.assertEqual(user.display_name, 'Test Buddy')
user = graphrbac_client.user.get(user.object_id)
self.assertEqual(user.display_name, 'Test Buddy')
graphrbac_client.user_operations.delete(user.object_id)
Service Bus
ServiceBus Queues
ServiceBus Queues are an alternative to Storage Queues that might be useful in scenarios where more advanced
messaging features are needed (larger message sizes, message ordering, single-operaiton destructive reads, scheduled
delivery) using push-style delivery (using long polling).
The service can use Shared Access Signature authentication, or ACS authentication.
Service bus namespaces created using the Azure portal after August 2014 no longer support ACS authentication. You
can create ACS compatible namespaces with the Azure SDK.
To use Shared Access Signature authentication, create the service bus service with:
ACS Authentication
sbs.create_queue('taskqueue')
The send_queue_message method can then be called to insert the message into the queue:
The send_queue_message_batch method can then be called to send several messages at once:
msg = sbs.receive_queue_message('taskqueue')
ServiceBus Topics
ServiceBus topics are an abstraction on top of ServiceBus Queues that make pub/sub scenarios easy to implement.
The create_topic method can be used to create a server-side topic:
sbs.create_topic('taskdiscussion')
Please consider that in Python 3 a str message will be utf-8 encoded and you should have to manage your encoding
yourself in Python 2.
A client can then create a subscription and start consuming messages by calling the create_subscription method
followed by the receive_subscription_message method. Please note that any messages sent before the subscription is
created will not be received.
sbs.create_subscription('taskdiscussion', 'client1')
msg = Message('Hello World!')
sbs.send_topic_message('taskdiscussion', msg)
msg = sbs.receive_subscription_message('taskdiscussion', 'client1')
Event Hub
Event Hubs enable the collection of event streams at high throughput, from a diverse set of devices and services.
The create_event_hub method can be used to create an event hub:
sbs.create_event_hub('myhub')
To send an event:
sbs.send_event('myhub', '{ "DeviceId":"dev-01", "Temperature":"37.0" }')
The event content is the event message or JSON-encoded string that contains multiple messages.
Advanced features
This section describes how to use Broker and User properties defined here: https://docs.microsoft.com/rest/api/
servicebus/message-headers-and-properties
sent_msg = Message(b'This is the third message',
broker_properties={'Label': 'M3'},
custom_properties={'Priority': 'Medium',
'Customer': 'ABC'}
)
For compatibility reason with old version of this library, broker_properties could also be defined as a JSON string. If
this situation, you’re responsible to write a valid JSON string, no check will be made by Python before sending to the
RestAPI.
broker_properties = '{"ForcePersistence": false, "Label": "My label"}'
sent_msg = Message(b'receive message',
broker_properties = broker_properties
)
azure.common package
Submodules
Module contents
azure.batch package
Submodules
azure.batch.models module
azure.batch.operations module
Module contents
azure.graphrbac package
Submodules
azure.graphrbac.models module
azure.graphrbac.operations module
Module contents
azure.keyvault package
Submodules
azure.keyvault.key_vault_id module
Module contents
azure.keyvault.generated package
Submodules
azure.keyvault.generated.models module
Module contents
Module contents
azure.mgmt.authorization package
Submodules
azure.mgmt.authorization.models module
azure.mgmt.authorization.operations module
Module contents
azure.mgmt.batch package
Submodules
azure.mgmt.batch.models module
azure.mgmt.batch.operations module
Module contents
azure.mgmt.cdn package
Submodules
azure.mgmt.cdn.models module
azure.mgmt.cdn.operations module
Module contents
azure.mgmt.cognitiveservices package
Submodules
azure.mgmt.cognitiveservices.models module
azure.mgmt.cognitiveservices.operations module
Module contents
azure.mgmt.commerce package
Submodules
azure.mgmt.commerce.models module
azure.mgmt.commerce.operations module
Module contents
azure.mgmt.compute.compute package
Module contents
Submodules
azure.mgmt.compute.compute.v2016_04_30_preview package
Submodules
azure.mgmt.compute.compute.v2016_04_30_preview.models module
azure.mgmt.compute.compute.v2016_04_30_preview.operations module
Module contents
azure.mgmt.compute.compute.v2015_06_15 package
Submodules
azure.mgmt.compute.compute.v2015_06_15.models module
azure.mgmt.compute.compute.v2015_06_15.operations module
Module contents
azure.mgmt.compute.containerservice package
Module contents
Submodules
azure.mgmt.compute.containerservice.v2017_01_31 package
Submodules
azure.mgmt.compute.containerservice.v2017_01_31.models module
azure.mgmt.compute.containerservice.v2017_01_31.operations module
Module contents
azure.mgmt.containerregistry package
Submodules
azure.mgmt.containerregistry.models module
azure.mgmt.containerregistry.operations module
Module contents
azure.mgmt.datalake.analytics.account package
Submodules
azure.mgmt.datalake.analytics.account.models module
azure.mgmt.datalake.analytics.account.operations module
Module contents
azure.mgmt.datalake.analytics.catalog package
Submodules
azure.mgmt.datalake.analytics.catalog.models module
azure.mgmt.datalake.analytics.catalog.operations module
Module contents
azure.mgmt.datalake.analytics.job package
Submodules
azure.mgmt.datalake.analytics.job.models module
azure.mgmt.datalake.analytics.job.operations module
Module contents
azure.mgmt.datalake.store package
Submodules
azure.mgmt.datalake.store.models module
azure.mgmt.datalake.store.operations module
Module contents
azure.mgmt.devtestlabs package
Submodules
azure.mgmt.devtestlabs.models module
azure.mgmt.devtestlabs.operations module
Module contents
azure.mgmt.dns package
Submodules
azure.mgmt.dns.models module
azure.mgmt.dns.operations module
Module contents
azure.mgmt.documentdb package
Submodules
azure.mgmt.documentdb.models module
azure.mgmt.documentdb.operations module
Module contents
azure.mgmt.eventhub package
Submodules
azure.mgmt.eventhub.models module
azure.mgmt.eventhub.operations module
Module contents
azure.mgmt.iothub package
Submodules
azure.mgmt.iothub.models module
azure.mgmt.iothub.operations module
Module contents
azure.mgmt.keyvault package
Submodules
azure.mgmt.keyvault.models module
azure.mgmt.keyvault.operations module
Module contents
azure.mgmt.logic package
Submodules
azure.mgmt.logic.models module
azure.mgmt.logic.operations module
Module contents
azure.mgmt.media package
Submodules
azure.mgmt.media.models module
azure.mgmt.media.operations module
Module contents
azure.mgmt.monitor package
Submodules
azure.mgmt.monitor.models module
azure.mgmt.monitor.operations module
Module contents
azure.mgmt.network package
Module contents
Submodules
azure.mgmt.network.v2017_03_01 package
Submodules
azure.mgmt.network.v2017_03_01.models module
azure.mgmt.network.v2017_03_01.operations module
Module contents
azure.mgmt.network.v2016_12_01 package
Submodules
azure.mgmt.network.v2016_12_01.models module
azure.mgmt.network.v2016_12_01.operations module
Module contents
azure.mgmt.network.v2016_09_01 package
Submodules
azure.mgmt.network.v2016_09_01.models module
azure.mgmt.network.v2016_09_01.operations module
Module contents
azure.mgmt.network.v2015_06_15 package
Submodules
azure.mgmt.network.v2015_06_15.models module
azure.mgmt.network.v2015_06_15.operations module
Module contents
azure.mgmt.notificationhubs package
Submodules
azure.mgmt.notificationhubs.models module
azure.mgmt.notificationhubs.operations module
Module contents
azure.mgmt.powerbiembedded package
Submodules
azure.mgmt.powerbiembedded.models module
azure.mgmt.powerbiembedded.operations module
Module contents
azure.mgmt.redis package
Submodules
azure.mgmt.redis.models module
azure.mgmt.redis.operations module
Module contents
azure.mgmt.resource.features package
Module contents
Submodules
azure.mgmt.resource.features.v2015_12_01 package
Submodules
azure.mgmt.resource.features.v2015_12_01.models module
azure.mgmt.resource.features.v2015_12_01.operations module
Module contents
azure.mgmt.resource.links package
Module contents
Submodules
azure.mgmt.resource.links.v2016_09_01 package
Submodules
azure.mgmt.resource.links.v2016_09_01.models module
azure.mgmt.resource.links.v2016_09_01.operations module
Module contents
azure.mgmt.resource.locks package
Module contents
Submodules
azure.mgmt.resource.locks.v2016_09_01 package
Submodules
azure.mgmt.resource.locks.v2016_09_01.models module
azure.mgmt.resource.locks.v2016_09_01.operations module
Module contents
azure.mgmt.resource.locks.v2015_01_01 package
Submodules
azure.mgmt.resource.locks.v2015_01_01.models module
azure.mgmt.resource.locks.v2015_01_01.operations module
Module contents
azure.mgmt.resource.policy package
Module contents
Submodules
azure.mgmt.resource.policy.v2016_12_01 package
Submodules
azure.mgmt.resource.policy.v2016_12_01.models module
azure.mgmt.resource.policy.v2016_12_01.operations module
Module contents
azure.mgmt.resource.policy.v2016_04_01 package
Submodules
azure.mgmt.resource.policy.v2016_04_01.models module
azure.mgmt.resource.policy.v2016_04_01.operations module
Module contents
azure.mgmt.resource.resources package
Module contents
Submodules
azure.mgmt.resource.resources.v2016_09_01 package
Submodules
azure.mgmt.resource.resources.v2016_09_01.models module
azure.mgmt.resource.resources.v2016_09_01.operations module
Module contents
azure.mgmt.resource.resources.v2016_02_01 package
Submodules
azure.mgmt.resource.resources.v2016_02_01.models module
azure.mgmt.resource.resources.v2016_02_01.operations module
Module contents
azure.mgmt.resource.subscriptions package
Module contents
Submodules
azure.mgmt.resource.subscriptions.v2016_06_01 package
Submodules
azure.mgmt.resource.subscriptions.v2016_06_01.models module
azure.mgmt.resource.subscriptions.v2016_06_01.operations module
Module contents
azure.mgmt.scheduler package
Submodules
azure.mgmt.scheduler.models module
azure.mgmt.scheduler.operations module
Module contents
azure.mgmt.search package
Submodules
azure.mgmt.search.models module
azure.mgmt.search.operations module
Module contents
azure.mgmt.servermanager package
Submodules
azure.mgmt.servermanager.models module
azure.mgmt.servermanager.operations module
Module contents
azure.mgmt.servicebus package
Submodules
azure.mgmt.servicebus.models module
azure.mgmt.servicebus.operations module
Module contents
azure.mgmt.sql package
Submodules
azure.mgmt.sql.models module
azure.mgmt.sql.operations module
Module contents
azure.mgmt.storage package
Module contents
Submodules
azure.mgmt.storage.v2016_12_01 package
Submodules
azure.mgmt.storage.v2016_12_01.models module
azure.mgmt.storage.v2016_12_01.operations module
Module contents
azure.mgmt.storage.v2015_06_15 package
Submodules
azure.mgmt.storage.v2015_06_15.models module
azure.mgmt.storage.v2015_06_15.operations module
Module contents
azure.mgmt.trafficmanager package
Submodules
azure.mgmt.trafficmanager.models module
azure.mgmt.trafficmanager.operations module
Module contents
azure.mgmt.web package
Submodules
azure.mgmt.web.models module
azure.mgmt.web.operations module
Module contents
azure.monitor package
Submodules
azure.monitor.models module
azure.monitor.operations module
Module contents
azure.servicebus package
Submodules
azure.servicebus.constants module
azure.servicebus.models module
azure.servicebus.servicebusservice module
Module contents
azure.servicemanagement package
Submodules
azure.servicemanagement.constants module
azure.servicemanagement.models module
azure.servicemanagement.publishsettings module
azure.servicemanagement.schedulermanagementservice module
azure.servicemanagement.servicebusmanagementservice module
azure.servicemanagement.servicemanagementclient module
azure.servicemanagement.servicemanagementservice module
azure.servicemanagement.sqldatabasemanagementservice module
azure.servicemanagement.websitemanagementservice module
Module contents