0

I want to programmatically give an Azure VM a contributor role to another modify things in another resources such as Route tables, Storage accounts.

https://learn.microsoft.com/en-us/azure/active-directory/managed-service-identity/howto-assign-access-cli

Above msft doc explain how one can give MSI enabled VM a contributor role to Azure Storage Account using Azure CLI. Can someone achieve the same using Azure Python SDK instead of Azure CLI ? Is it possible to achieve the same purpose without enabling MSI?

explorer
  • 737
  • 1
  • 8
  • 23

1 Answers1

1

If you create a Service Principal for your VM, and push somehow the credentials on the VM, you can avoid MSI. But MSI was created on purpose to avoid that, since it's not really a simple process nor safe to push credentials inside a VM.

To assign a role to an Active Directory ID (whatever using MSI or dedicated ServicePrincipal), you can use this code to assign role (using azure-mgmt-authorization package).

https://github.com/Azure-Samples/compute-python-msi-vm#role-assignement-to-the-msi-credentials

# Get "Contributor" built-in role as a RoleDefinition object
role_name = 'Contributor'
roles = list(authorization_client.role_definitions.list(
    resource_group.id,
    filter="roleName eq '{}'".format(role_name)
))
assert len(roles) == 1
contributor_role = roles[0]

# Add RG scope to the AD id
# This assumes "sp_id" is either a MSI id or a SP id
role_assignment = authorization_client.role_assignments.create(
    resource_group.id,
    uuid.uuid4(), # Role assignment random name
    {
        'role_definition_id': contributor_role.id,
        'principal_id': sp_id
    }
)

Then this AD id will be able to act only on that role and nothing more.

Laurent Mazuel
  • 3,422
  • 13
  • 27
  • Thanks Laurent! and if you want to limit the scope to particular resource instead of RG, I suppose you can still do it by replace "resource_group.id" to "resource.id" in above example. – explorer Jul 19 '18 at 04:07
  • How would you get "authorization_client" object we are using? – explorer Jul 19 '18 at 04:12
  • https://learn.microsoft.com/en-us/python/api/overview/azure/authorization?view=azure-python – Laurent Mazuel Jul 23 '18 at 17:10