msrestazure package

Submodules

msrestazure.azure_active_directory module

class msrestazure.azure_active_directory.AADMixin(client_id, token)[source]

Bases: msrest.authentication.OAuthTokenAuthentication

Mixin for Authentication object. Provides some AAD functionality: - State validation - Token caching and retrieval - Default AAD configuration

clear_cached_token()[source]

Clear any stored tokens.

Raises:KeyError if failed to clear token.
Return type:None
signed_session()[source]

Create token-friendly Requests session, using auto-refresh. Used internally when a request is made.

Return type:requests_oauthlib.OAuth2Session
Raises:TokenExpiredError if token can no longer be refreshed.
class msrestazure.azure_active_directory.AADRefreshMixin[source]

Bases: object

Additional token refresh logic

refresh_session()[source]

Return updated session if token has expired, attempts to refresh using newly acquired token.

Return type:requests.Session.
class msrestazure.azure_active_directory.AADTokenCredentials(token, client_id=None, **kwargs)[source]

Bases: msrestazure.azure_active_directory.AADMixin

Credentials objects for AAD token retrieved through external process e.g. Python ADAL lib.

Optional kwargs may include: - cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment - china (bool): Configure auth for China-based service,

default is ‘False’.
  • tenant (str): Alternative tenant, default is ‘common’.
  • auth_uri (str): Alternative authentication endpoint.
  • token_uri (str): Alternative token retrieval endpoint.
  • resource (str): Alternative authentication resource, default is ‘https://management.core.windows.net/‘.
  • verify (bool): Verify secure connection, default is ‘True’.
  • keyring (str): Name of local token cache, default is ‘AzureAAD’.
  • cached (bool): If true, will not attempt to collect a token, which can then be populated later from a cached token.
Parameters:
  • token (dict) – Authentication token.
  • client_id (str) – Client ID, if not set, Xplat Client ID will be used.
classmethod retrieve_session(client_id=None)[source]

Create AADTokenCredentials from a cached token if it has not yet expired.

class msrestazure.azure_active_directory.AdalAuthentication(adal_method, *args, **kwargs)[source]

Bases: msrest.authentication.Authentication

A wrapper to use ADAL for Python easily to authenticate on Azure.

New in version 0.4.5.

Take an ADAL acquire_token method and its parameters.

Example:
context = adal.AuthenticationContext('https://login.microsoftonline.com/ABCDEFGH-1234-1234-1234-ABCDEFGHIJKL')
RESOURCE = '00000002-0000-0000-c000-000000000000' #AAD graph resource
token = context.acquire_token_with_client_credentials(
    RESOURCE,
    "http://PythonSDK",
    "Key-Configured-In-Portal")

can be written here:

context = adal.AuthenticationContext('https://login.microsoftonline.com/ABCDEFGH-1234-1234-1234-ABCDEFGHIJKL')
RESOURCE = '00000002-0000-0000-c000-000000000000' #AAD graph resource
credentials = AdalAuthentication(
    context.acquire_token_with_client_credentials,
    RESOURCE,
    "http://PythonSDK",
    "Key-Configured-In-Portal")

or using a lambda if you prefer:

context = adal.AuthenticationContext('https://login.microsoftonline.com/ABCDEFGH-1234-1234-1234-ABCDEFGHIJKL')
RESOURCE = '00000002-0000-0000-c000-000000000000' #AAD graph resource
credentials = AdalAuthentication(
    lambda: context.acquire_token_with_client_credentials(
        RESOURCE,
        "http://PythonSDK",
        "Key-Configured-In-Portal"
    )
)
Parameters:
  • adal_method – A lambda with no args, or acquire_token method with args using args/kwargs
  • args – Optional args for the method
  • kwargs – Optional kwargs for the method
signed_session()[source]

Get a signed session for requests.

Usually called by the Azure SDKs for you to authenticate queries.

Return type:requests.Session
class msrestazure.azure_active_directory.InteractiveCredentials(*args, **kwargs)[source]

Bases: object

class msrestazure.azure_active_directory.MSIAuthentication(port=50342, **kwargs)[source]

Bases: msrest.authentication.BasicTokenAuthentication

Credentials object for MSI authentication,.

Optional kwargs may include: - cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment - resource (str): Alternative authentication resource, default

Parameters:port (int) – MSI local port if VM/VMSS context (ignored otherwise)
set_token()[source]
signed_session()[source]
class msrestazure.azure_active_directory.ServicePrincipalCredentials(client_id, secret, **kwargs)[source]

Bases: msrestazure.azure_active_directory.AADRefreshMixin, msrestazure.azure_active_directory.AADMixin

Credentials object for Service Principle Authentication. Authenticates via a Client ID and Secret.

Optional kwargs may include: - cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment - china (bool): Configure auth for China-based service,

default is ‘False’.
  • tenant (str): Alternative tenant, default is ‘common’.
  • auth_uri (str): Alternative authentication endpoint.
  • token_uri (str): Alternative token retrieval endpoint.
  • resource (str): Alternative authentication resource, default is ‘https://management.core.windows.net/‘.
  • verify (bool): Verify secure connection, default is ‘True’.
  • keyring (str): Name of local token cache, default is ‘AzureAAD’.
  • timeout (int): Timeout of the request in seconds.
  • cached (bool): If true, will not attempt to collect a token, which can then be populated later from a cached token.
  • proxies (dict): Dictionary mapping protocol or protocol and hostname to the URL of the proxy.
Parameters:
  • client_id (str) – Client ID.
  • secret (str) – Client secret.
classmethod retrieve_session(client_id)[source]

Create ServicePrincipalCredentials from a cached token if it has not yet expired.

set_token()[source]

Get token using Client ID/Secret credentials.

Raises:AuthenticationError if credentials invalid, or call fails.
class msrestazure.azure_active_directory.UserPassCredentials(username, password, client_id=None, secret=None, **kwargs)[source]

Bases: msrestazure.azure_active_directory.AADRefreshMixin, msrestazure.azure_active_directory.AADMixin

Credentials object for Headless Authentication, i.e. AAD authentication via username and password.

Headless Auth requires an AAD login (no a Live ID) that already has permission to access the resource e.g. an organization account, and that 2-factor auth be disabled.

Optional kwargs may include: - cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment - china (bool): Configure auth for China-based service,

default is ‘False’.
  • tenant (str): Alternative tenant, default is ‘common’.
  • auth_uri (str): Alternative authentication endpoint.
  • token_uri (str): Alternative token retrieval endpoint.
  • resource (str): Alternative authentication resource, default is ‘https://management.core.windows.net/‘.
  • verify (bool): Verify secure connection, default is ‘True’.
  • keyring (str): Name of local token cache, default is ‘AzureAAD’.
  • timeout (int): Timeout of the request in seconds.
  • cached (bool): If true, will not attempt to collect a token, which can then be populated later from a cached token.
  • proxies (dict): Dictionary mapping protocol or protocol and hostname to the URL of the proxy.
Parameters:
  • username (str) – Account username.
  • password (str) – Account password.
  • client_id (str) – Client ID, if not set, Xplat Client ID will be used.
  • secret (str) – Client secret, only if required by server.
classmethod retrieve_session(username, client_id=None)[source]

Create ServicePrincipalCredentials from a cached token if it has not yet expired.

set_token()[source]

Get token using Username/Password credentials.

Raises:AuthenticationError if credentials invalid, or call fails.
msrestazure.azure_active_directory.get_msi_token(resource, port=50342)[source]
msrestazure.azure_active_directory.get_msi_token_webapp(resource)[source]

Get a MSI token from inside a webapp or functions.

Env variable will look like: MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/ MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB

msrestazure.azure_configuration module

class msrestazure.azure_configuration.AzureConfiguration(base_url, filepath=None)[source]

Bases: msrest.configuration.Configuration

Azure specific client configuration.

Parameters:
  • base_url (str) – REST Service base URL.
  • filepath (str) – Path to an existing config file (optional).
load(filepath)[source]

Load configuration from existing file.

Parameters:filepath (str) – Path to existing config file.
Raises:ValueError if supplied config file is invalid.
Return type:None
save(filepath)[source]

Save current configuration to file.

Parameters:filepath (str) – Path to save file to.
Raises:ValueError if supplied filepath cannot be written to.
Return type:None

msrestazure.azure_exceptions module

exception msrestazure.azure_exceptions.CloudError(response, error=None, *args, **kwargs)[source]

Bases: msrest.exceptions.ClientException

ClientError, exception raised for failed Azure REST call. Will attempt to deserialize response into meaningful error data.

Parameters:
class msrestazure.azure_exceptions.CloudErrorData(*args, **kwargs)[source]

Bases: object

Cloud Error Data object, deserialized from error data returned during a failed REST API call.

message

Cloud error message.

class msrestazure.azure_exceptions.CloudErrorRoot(error)[source]

Bases: object

Just match the “error” key at the root of a OdataV4 JSON.

msrestazure.azure_operation module

class msrestazure.azure_operation.AzureOperationPoller(send_cmd, output_cmd, update_cmd, timeout=30)[source]

Bases: object

Initiates long running operation and polls status in separate thread.

Parameters:
  • send_cmd (callable) – The API request to initiate the operation.
  • update_cmd (callable) – The API reuqest to check the status of the operation.
  • output_cmd (callable) – The function to deserialize the resource of the operation.
  • timeout (int) – Time in seconds to wait between status calls, default is 30.
add_done_callback(func)[source]

Add callback function to be run once the long running operation has completed - regardless of the status of the operation.

Parameters:func (callable) – Callback function that takes at least one argument, a completed LongRunningOperation.
Raises:ValueError if the long running operation has already completed.
done()[source]

Check status of the long running operation.

Returns:‘True’ if the process has completed, else ‘False’.
remove_done_callback(func)[source]

Remove a callback from the long running operation.

Parameters:func (callable) – The function to be removed from the callbacks.
Raises:ValueError if the long running operation has already completed.
result(timeout=None)[source]

Return the result of the long running operation, or the result available after the specified timeout.

Returns:The deserialized resource of the long running operation, if one is available.
Raises:CloudError – Server problem with the query.
status()[source]

Returns the current status string.

Returns:The current status string
Return type:str
wait(timeout=None)[source]

Wait on the long running operation for a specified length of time.

Parameters:timeout (int) – Perion of time to wait for the long running operation to complete.
Raises:CloudError – Server problem with the query.
exception msrestazure.azure_operation.BadResponse[source]

Bases: exceptions.Exception

exception msrestazure.azure_operation.BadStatus[source]

Bases: exceptions.Exception

class msrestazure.azure_operation.LongRunningOperation(response, outputs)[source]

Bases: object

Provides default logic for interpreting operation responses and status updates.

get_status_from_async(response)[source]

Process the latest status update retrieved from a ‘azure-asyncoperation’ header.

Parameters:response (requests.Response) – latest REST call response.
Raises:BadResponse if response has no body, or body does not contain status.
get_status_from_location(response)[source]

Process the latest status update retrieved from a ‘location’ header.

Parameters:response (requests.Response) – latest REST call response.
Raises:BadResponse if response has no body and not status 202.
get_status_from_resource(response)[source]

Process the latest status update retrieved from the same URL as the previous request.

Parameters:response (requests.Response) – latest REST call response.
Raises:BadResponse if status not 200 or 204.
set_async_url_if_present(response)[source]
set_initial_status(response)[source]

Process first response after initiating long running operation and set self.status attribute.

Parameters:response (requests.Response) – initial REST call response.
should_do_final_get()[source]

Check whether the polling should end doing a final GET.

Parameters:response (requests.Response) – latest REST call response.
Return type:bool
exception msrestazure.azure_operation.OperationFailed[source]

Bases: exceptions.Exception

class msrestazure.azure_operation.SimpleResource(**kwargs)[source]

An implementation of Python 3 SimpleNamespace. Used to deserialize resource objects from response bodies where no particular object type has been specified.

msrestazure.azure_operation.failed(status)[source]
msrestazure.azure_operation.finished(status)[source]
msrestazure.azure_operation.succeeded(status)[source]

msrestazure.version module

msrestazure.tools module

msrestazure.tools.is_valid_resource_id(rid, exception_type=None)[source]

Validates the given resource id.

Parameters:
  • rid (str) – The resource id being validated.
  • exception_type (Exception) – Raises this Exception if invalid.
Returns:

A boolean describing whether the id is valid.

Return type:

bool

msrestazure.tools.parse_resource_id(rid)[source]

Parses a resource_id into its various parts.

Returns a dictionary with a single key-value pair, ‘name’: rid, if invalid resource id.

Parameters:rid (str) – The resource id being parsed
Returns:A dictionary with with following key/value pairs (if found):
  • subscription: Subscription id
  • resource_group: Name of resource group
  • namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
  • type: Type of the root resource (i.e. virtualMachines)
  • name: Name of the root resource
  • child_namespace_{level}: Namespace for the child resoure of that level
  • child_type_{level}: Type of the child resource of that level
  • child_name_{level}: Name of the child resource of that level
  • resource_parent: Computed parent in the following pattern: providers/{namespace} /{parent}/{type}/{name}
  • resource_namespace: Same as namespace. Note that this may be different than the target resource’s namespace.
  • resource_type: Type of the target resource (not the parent)
  • resource_name: Name of the target resource (not the parent)
Return type:dict
msrestazure.tools.register_rp_hook(r, *args, **kwargs)[source]

This is a requests hook to register RP automatically.

See requests documentation for details of the signature of this function. http://docs.python-requests.org/en/master/user/advanced/#event-hooks

msrestazure.tools.resource_id(**kwargs)[source]

Create a valid resource id string from the given parts.

This method builds the resource id from the left until the next required id parameter to be appended is not found. It then returns the built up id.

Parameters:kwargs (dict) –

The keyword arguments that will make up the id.

The method accepts the following keyword arguments:
  • subscription (required): Subscription id
  • resource_group: Name of resource group
  • namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
  • type: Type of the resource (i.e. virtualMachines)
  • name: Name of the resource (or parent if child_name is also specified)
  • child_namespace_{level}: Namespace for the child resoure of that level (optional)
  • child_type_{level}: Type of the child resource of that level
  • child_name_{level}: Name of the child resource of that level
Returns:A resource id built from the given arguments.
Return type:str

Module contents

class msrestazure.AzureConfiguration(base_url, filepath=None)[source]

Bases: msrest.configuration.Configuration

Azure specific client configuration.

Parameters:
  • base_url (str) – REST Service base URL.
  • filepath (str) – Path to an existing config file (optional).
load(filepath)[source]

Load configuration from existing file.

Parameters:filepath (str) – Path to existing config file.
Raises:ValueError if supplied config file is invalid.
Return type:None
save(filepath)[source]

Save current configuration to file.

Parameters:filepath (str) – Path to save file to.
Raises:ValueError if supplied filepath cannot be written to.
Return type:None