Use MSI to authenticate simply from inside a VM

Utolsó frissítés: 2017.09.14.
Szerkesztés a GitHubon

This sample explains how to use the SDK from inside an Azure resource like a VM, using Managed Service Identity (MSI) authentication.

On this page

Run this sample

  1. This sample is intended to be executed from inside a VM with MSI enabled. This document explains how to create a VM with MSI enabled.

  2. If you don't already have it, install Python on that VM.

  3. We recommend to use a virtual environnement to run this example, but it's not mandatory. You can initialize a virtualenv this way:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  4. Clone the repository.

    git clone https://github.com/Azure-Samples/resource-manager-python-manage-resources-with-msi.git
    
  5. Install the dependencies using pip.

    cd resource-manager-python-manage-resources-with-msi
    pip install -r requirements.txt
    
  6. Run the sample.

    python example.py
    

What is example.py doing?

The sample creates a MSI Authentication credentials class. Then it uses this credentials to extract the current subscription ID. Finally it uses this credentials and subscription ID to list all the available Resource Groups.

Note that listing Resource Group is just an example, there is no actual limit of what you can do with this credentials (creating a KeyVault account, managing the Network of your VMs, etc.). The limit will be defined by the roles and policy assigned to the MSI token at the time of the creation of the VM.

Create a MSI authentication instance

from msrestazure.azure_active_directory import MSIAuthentication

credentials = MSIAuthentication()

Get the subscription ID of that token

from azure.mgmt.resource import SubscriptionClient

subscription_client = SubscriptionClient(credentials)
subscription = next(subscription_client.subscriptions.list())
subscription_id = subscription.subscription_id

List resource groups

List the resource groups in your subscription.

from azure.mgmt.resource import ResourceManagementClient

resource_client = ResourceManagementClient(credentials, subscription_id)
for item in resource_client.resource_groups.list():
    print(resource_group.name)