|
| 1 | +"""A program to demonstrate accessing Azure Python SDK""" |
| 2 | + |
| 3 | +from azure.core.credentials import AccessToken |
| 4 | +from azure.mgmt.authorization import AuthorizationManagementClient |
| 5 | +from pulumi_azure_native import authorization, containerregistry, resources |
| 6 | + |
| 7 | + |
| 8 | +class TokenCred: |
| 9 | + def __init__(self, token): |
| 10 | + self.token = token |
| 11 | + |
| 12 | + def get_token(self, *scopes, **kwargs) -> 'AccessToken': |
| 13 | + return AccessToken(token=self.token, expires_on=-1) |
| 14 | + |
| 15 | + |
| 16 | +def get_role_id_by_name(name, scope=""): |
| 17 | + config = authorization.get_client_config() |
| 18 | + client_token = authorization.get_client_token() |
| 19 | + client = AuthorizationManagementClient( |
| 20 | + TokenCred(client_token.token), config.subscription_id) |
| 21 | + def_pages = client.role_definitions.list( |
| 22 | + scope, filter=f'roleName eq {name}') |
| 23 | + role = None |
| 24 | + for x in def_pages: |
| 25 | + role = x.id |
| 26 | + break |
| 27 | + if role is None: |
| 28 | + raise Exception(f'role \'{name}\' not found at scope \'{scope}\'') |
| 29 | + return role |
| 30 | + |
| 31 | + |
| 32 | +# Create an Azure Resource Group |
| 33 | +resource_group = resources.ResourceGroup('resource_group') |
| 34 | + |
| 35 | +# Create a container registry |
| 36 | +container_registry = containerregistry.Registry( |
| 37 | + 'registry', |
| 38 | + resource_group_name=resource_group.name, |
| 39 | + sku=containerregistry.SkuArgs(name='Basic'), |
| 40 | + admin_user_enabled=True) |
| 41 | + |
| 42 | +client_config = authorization.get_client_config() |
| 43 | +current_principal = client_config.object_id |
| 44 | + |
| 45 | +roledef = get_role_id_by_name('AcrPull') |
| 46 | + |
| 47 | +authorization.RoleAssignment("access-from-cluster", |
| 48 | + principal_id=current_principal, |
| 49 | + # adjust this if running as service principal |
| 50 | + principal_type=authorization.PrincipalType.USER, |
| 51 | + role_definition_id=roledef, |
| 52 | + scope=container_registry.id) |
0 commit comments