def applicationinsights_mgmt_plane_client(cli_ctx, _, subscription=None): """Initialize Log Analytics mgmt client for use with CLI.""" from .vendored_sdks.mgmt_applicationinsights import ApplicationInsightsManagementClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) # Use subscription from resource_id where possible, otherwise use login. if subscription: cred, _, _ = profile.get_login_credentials( subscription_id=subscription) return ApplicationInsightsManagementClient(cred, subscription) cred, sub_id, _ = profile.get_login_credentials() return ApplicationInsightsManagementClient(cred, sub_id)
def setup_continuous_delivery(self, cli_ctx, resource_group_name, name, repo_url, branch, git_token, slot, cd_app_type_details, cd_project_url, cd_create_account, location, test, private_repo_username, private_repo_password, webapp_list): """ This method sets up CD for an Azure Web App thru Team Services """ # Gather information about the Azure connection profile = Profile(cli_ctx=cli_ctx) subscription = profile.get_subscription() user = profile.get_current_account_user() cred, _, _ = profile.get_login_credentials(subscription_id=None) cd_manager = ContinuousDeliveryManager(self._update_progress) # Generate an Azure token with the VSTS resource app id auth_token = profile.get_access_token_for_resource(user, None, cd_manager.get_vsts_app_id()) cd_manager.set_repository_info(repo_url, branch, git_token, private_repo_username, private_repo_password) cd_manager.set_azure_web_info(resource_group_name, name, cred, subscription['id'], subscription['name'], subscription['tenantId'], location) vsts_cd_status = cd_manager.setup_continuous_delivery(slot, cd_app_type_details, cd_project_url, cd_create_account, auth_token, test, webapp_list) return vsts_cd_status
def get_appconfig_data_client(cmd, name, connection_string, auth_mode, endpoint): azconfig_client = None if auth_mode == "key": connection_string = resolve_connection_string(cmd, name, connection_string) try: azconfig_client = AzureAppConfigurationClient.from_connection_string(connection_string=connection_string, user_agent=HttpHeaders.USER_AGENT) except ValueError as ex: raise CLIError("Failed to initialize AzureAppConfigurationClient due to an exception: {}".format(str(ex))) if auth_mode == "login": if not endpoint: try: if name: _, endpoint = resolve_store_metadata(cmd, name) else: raise CLIError("App Configuration endpoint or name should be provided if auth mode is 'login'.") except Exception as ex: raise CLIError(str(ex) + "\nYou may be able to resolve this issue by providing App Configuration endpoint instead of name.") from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cmd.cli_ctx) cred, _, _ = profile.get_login_credentials() try: azconfig_client = AzureAppConfigurationClient(credential=cred, base_url=endpoint, user_agent=HttpHeaders.USER_AGENT) except (ValueError, TypeError) as ex: raise CLIError("Failed to initialize AzureAppConfigurationClient due to an exception: {}".format(str(ex))) return azconfig_client
def validate_lab_vm_list(namespace): """ Validates parameters for lab vm list and updates namespace. """ collection = [namespace.filters, namespace.all, namespace.claimable] if _any(collection) and not _single(collection): raise CLIError("usage error: [--filters FILTER | --all | --claimable]") # Retrieve all the vms of the lab if namespace.all: namespace.filters = None # Retrieve all the vms claimable by user elif namespace.claimable: namespace.filters = 'properties/allowClaim' # Default to retrieving users vms only else: # Find out owner object id if not namespace.object_id: from azure.cli.core._profile import Profile, CLOUD from azure.graphrbac.models import GraphErrorException profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient(cred, tenant_id, base_url=CLOUD.endpoints.active_directory_graph_resource_id) subscription = profile.get_subscription() try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) namespace.filters = "Properties/ownerObjectId eq '{}'".format(object_id)
def validate_lab_vm_list(namespace): """ Validates parameters for lab vm list and updates namespace. """ collection = [namespace.filters, namespace.all, namespace.claimable] if _any(collection) and not _single(collection): raise CLIError("usage error: [--filters FILTER | --all | --claimable]") # Retrieve all the vms of the lab if namespace.all: namespace.filters = None # Retrieve all the vms claimable by user elif namespace.claimable: namespace.filters = 'properties/allowClaim' # Default to retrieving users vms only else: # Find out owner object id if not namespace.object_id: from azure.cli.core._profile import Profile, CLOUD from azure.graphrbac.models import GraphErrorException profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient( cred, tenant_id, base_url=CLOUD.endpoints.active_directory_graph_resource_id) subscription = profile.get_subscription() try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) namespace.filters = "Properties/ownerObjectId eq '{}'".format( object_id)
def list_releases(target_name, target_resource_group): """ Lists all the release definitions that are deployed to a given Azure container service. :param target_name: Name of the target Azure container service instance. :type target_name: String :param target_resource_group: Name of Azure container service's resource group. :type target_resource_group: String """ profile = Profile() _, subscription_id, _ = profile.get_login_credentials() o_auth_token = _get_service_token() container_service_resource_id = CONTAINER_SERVICE_RESOURCE_URL.format(subscription_id=subscription_id, resource_group_name=target_resource_group, container_service_name=target_name) data = { 'acsResourceId': container_service_resource_id } list_releases_url = SERVICE_URL.format( subscription_id=subscription_id) + '/listReleases?api-version=' + API_VERSION headers = {} headers['Authorization'] = o_auth_token headers['Content-Type'] = 'application/json; charset=utf-8' headers['x-ms-client-request-id'] = str(uuid.uuid1()) req = requests.post(list_releases_url, data=json.dumps(data), headers=headers, timeout=600) while req.status_code == 202: # Long-running operation time.sleep(10) req = requests.get(BASE_URL + req.headers['Location'], headers=headers, timeout=600) if req.status_code != 200: raise CLIError( 'Server returned status code: ' + str(req.status_code) + '. Could not list releases: ' + req.text) json_request = req.json() return json_request
def batch_data_service_factory(cli_ctx, kwargs): import azure.batch.batch_service_client as batch import azure.batch.batch_auth as batchauth account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) account_endpoint = kwargs.pop('account_endpoint', None) kwargs.pop('yes', None) credentials = None if not account_key: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) # in order to use AAD auth in cloud shell mode, we will use mgmt AAD token # instead of Batch AAD token to auth if in_cloud_console(): resource = cli_ctx.cloud.endpoints.active_directory_resource_id else: resource = cli_ctx.cloud.endpoints.batch_resource_id credentials, _, _ = profile.get_login_credentials(resource=resource) else: credentials = batchauth.SharedKeyCredentials(account_name, account_key) if not (account_endpoint.startswith('https://') or account_endpoint.startswith('http://')): account_endpoint = 'https://' + account_endpoint return batch.BatchServiceClient(credentials, batch_url=account_endpoint.rstrip('/'))
def _get_mgmt_service_client(client_type, subscription_bound=True, subscription_id=None, api_version=None, base_url_bound=True, **kwargs): logger.debug('Getting management service client client_type=%s', client_type.__name__) profile = Profile() cred, subscription_id, _ = profile.get_login_credentials( subscription_id=subscription_id) client_kwargs = {} if base_url_bound: client_kwargs = {'base_url': CLOUD.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if kwargs: client_kwargs.update(kwargs) if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) configure_common_settings(client) return (client, subscription_id)
def _mock_get_mgmt_service_client(client_type, subscription_bound=True, subscription_id=None, api_version=None, base_url_bound=None, resource=CLOUD.endpoints.active_directory_resource_id, **kwargs): # version of _get_mgmt_service_client to use when recording or playing tests profile = Profile() cred, subscription_id, _ = profile.get_login_credentials(subscription_id=subscription_id, resource=resource) client_kwargs = {} if base_url_bound: client_kwargs = {'base_url': CLOUD.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if kwargs: client_kwargs.update(kwargs) if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) client = _debug.change_ssl_cert_verification(client) client.config.add_user_agent("AZURECLI/TEST/{}".format(core_version)) return (client, subscription_id)
def _graph_client_factory(**_): from azure.cli.core._profile import Profile profile = Profile() cred, _, tenant_id = profile.get_login_credentials(True) client = GraphRbacManagementClient(cred, tenant_id) configure_common_settings(client) return client
def _mock_get_mgmt_service_client(client_type, subscription_bound=True, subscription_id=None, api_version=None, base_url_bound=None, **kwargs): # version of _get_mgmt_service_client to use when recording or playing tests profile = Profile() cred, subscription_id, _ = profile.get_login_credentials( subscription_id=subscription_id) client_kwargs = {} if base_url_bound: client_kwargs = {'base_url': CLOUD.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if kwargs: client_kwargs.update(kwargs) if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) client = _debug.change_ssl_cert_verification(client) client.config.add_user_agent("AZURECLI/TEST/{}".format(core_version)) return (client, subscription_id)
def list_releases(target_name, target_resource_group): """ Lists all the release definitions that are deployed to a given Azure container service. :param target_name: Name of the target Azure container service instance. :type target_name: String :param target_resource_group: Name of Azure container service's resource group. :type target_resource_group: String """ profile = Profile() cred, subscription_id, _ = profile.get_login_credentials() o_auth_token = cred.signed_session().headers['Authorization'] container_service_resource_id = CONTAINER_SERVICE_RESOURCE_URL.format(subscription_id=subscription_id, resource_group_name=target_resource_group, container_service_name=target_name) data = { 'acsResourceId': container_service_resource_id } list_releases_url = SERVICE_URL.format( subscription_id=subscription_id) + '/listReleases?api-version=' + API_VERSION headers = {'Content-type': 'application/json', 'Authorization': o_auth_token} req = requests.post(list_releases_url, data=json.dumps(data), headers=headers, timeout=600) while req.status_code == 202: # Long-running operation time.sleep(10) req = requests.get(BASE_URL + req.headers['Location'], headers=headers, timeout=600) if req.status_code != 200: raise CLIError( 'Server returned status code: ' + str(req.status_code) + '. Could not list releases: ' + req.text) json_request = req.json() return json_request
def test_get_login_credentials(self, mock_get_token, mock_read_cred_file): some_token_type = 'Bearer' mock_read_cred_file.return_value = [Test_Profile.token_entry1] mock_get_token.return_value = (some_token_type, Test_Profile.raw_token1) #setup storage_mock = {'subscriptions': None} profile = Profile(storage_mock) consolidated = Profile._normalize_properties(self.user1, [self.subscription1], False) profile._set_subscriptions(consolidated) #action cred, subscription_id, _ = profile.get_login_credentials() #verify self.assertEqual(subscription_id, '1') #verify the cred._tokenRetriever is a working lambda token_type, token = cred._token_retriever() self.assertEqual(token, self.raw_token1) self.assertEqual(some_token_type, token_type) self.assertEqual(mock_read_cred_file.call_count, 1) mock_get_token.assert_called_once_with( mock.ANY, self.user1, self.tenant_id, 'https://management.core.windows.net/') self.assertEqual(mock_get_token.call_count, 1)
def _get_mgmt_service_client(client_type, subscription_bound=True, subscription_id=None, api_version=None, base_url_bound=True, resource=CLOUD.endpoints.active_directory_resource_id, **kwargs): logger.debug('Getting management service client client_type=%s', client_type.__name__) profile = Profile() cred, subscription_id, _ = profile.get_login_credentials(subscription_id=subscription_id, resource=resource) client_kwargs = {} if base_url_bound: client_kwargs = {'base_url': CLOUD.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if kwargs: client_kwargs.update(kwargs) if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) configure_common_settings(client) return (client, subscription_id)
def _get_data_credentials(cli_ctx, subscription_id=None): from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) creds, _, _ = profile.get_login_credentials( subscription_id=subscription_id, resource="https://quantum.microsoft.com") return creds
def batch_data_service_factory(cli_ctx, kwargs): import azure.batch.batch_service_client as batch import azure.batch.batch_auth as batchauth account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) account_endpoint = kwargs.pop('account_endpoint', None) kwargs.pop('yes', None) credentials = None if not account_key: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) # in order to use AAD auth in cloud shell mode, we will use mgmt AAD token # instead of Batch AAD token to auth if in_cloud_console(): resource = cli_ctx.cloud.endpoints.active_directory_resource_id else: resource = cli_ctx.cloud.endpoints.batch_resource_id credentials, _, _ = profile.get_login_credentials(resource=resource) else: # Verify all values are populated and display readable error if not all([account_name, account_key, account_endpoint]): raise ValueError( 'usage error: --account-name NAME --account-key KEY --account-endpoint ENDPOINT' ) credentials = batchauth.SharedKeyCredentials(account_name, account_key) if not (account_endpoint.startswith('https://') or account_endpoint.startswith('http://')): account_endpoint = 'https://' + account_endpoint return batch.BatchServiceClient(credentials, batch_url=account_endpoint.rstrip('/'))
def _get_login_account_principal_id(cli_ctx): from azure.graphrbac.models import GraphErrorException from azure.cli.core._profile import Profile, _USER_ENTITY, _USER_TYPE, _SERVICE_PRINCIPAL, _USER_NAME from azure.graphrbac import GraphRbacManagementClient profile = Profile(cli_ctx=cli_ctx) cred, _, tenant_id = profile.get_login_credentials( resource=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) client = GraphRbacManagementClient( cred, tenant_id, base_url=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) active_account = profile.get_subscription() assignee = active_account[_USER_ENTITY][_USER_NAME] try: if active_account[_USER_ENTITY][_USER_TYPE] == _SERVICE_PRINCIPAL: result = list( client.service_principals.list( filter=f"servicePrincipalNames/any(c:c eq '{assignee}')")) else: result = [client.signed_in_user.get()] except GraphErrorException as ex: logger.warning("Graph query error %s", ex) if not result: raise CLIInternalError(( f"Failed to retrieve principal id for '{assignee}', which is needed to create a " f"role assignment. Consider using '--principal-ids' to bypass the lookup" )) return result[0].object_id
def _get_mgmt_service_client(cli_ctx, client_type, subscription_bound=True, subscription_id=None, api_version=None, base_url_bound=True, resource=None, sdk_profile=None, **kwargs): from azure.cli.core._profile import Profile logger.debug('Getting management service client client_type=%s', client_type.__name__) resource = resource or cli_ctx.cloud.endpoints.active_directory_resource_id profile = Profile(cli_ctx=cli_ctx) cred, subscription_id, _ = profile.get_login_credentials( subscription_id=subscription_id, resource=resource) client_kwargs = {} if base_url_bound: client_kwargs = {'base_url': cli_ctx.cloud.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if sdk_profile: client_kwargs['profile'] = sdk_profile if kwargs: client_kwargs.update(kwargs) if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) configure_common_settings(cli_ctx, client) return client, subscription_id
def __init__(self, cli_ctx): profile = Profile(cli_ctx=cli_ctx) credentials, _, tenant_id = profile.get_login_credentials( resource=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) self.client = GraphRbacManagementClient( credentials, tenant_id, base_url=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) configure_common_settings(cli_ctx, self.client)
def create_keyvault(client, resource_group_name, vault_name, location=None, sku=SkuName.standard.value, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, no_self_perms=None, tags=None): from azure.mgmt.keyvault.models import VaultCreateOrUpdateParameters from azure.cli.core._profile import Profile, CLOUD from azure.graphrbac.models import GraphErrorException profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient( cred, tenant_id, base_url=CLOUD.endpoints.active_directory_graph_resource_id) subscription = profile.get_subscription() if no_self_perms: access_policies = [] else: permissions = Permissions(keys=[ KeyPermissions.get, KeyPermissions.create, KeyPermissions.delete, KeyPermissions.list, KeyPermissions.update, KeyPermissions.import_enum, KeyPermissions.backup, KeyPermissions.restore ], secrets=[SecretPermissions.all], certificates=[CertificatePermissions.all]) try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError( 'Cannot create vault.\nUnable to query active directory for information ' 'about the current user.\nYou may try the --no-self-perms flag to ' 'create a vault without permissions.') access_policies = [ AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions) ] properties = VaultProperties( tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment) parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)
def batch_data_service_factory(cli_ctx, kwargs): import azure.batch.batch_service_client as batch import azure.batch.batch_auth as batchauth account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) account_endpoint = kwargs.pop('account_endpoint', None) kwargs.pop('yes', None) credentials = None if not account_key: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) # in order to use AAD auth in cloud shell mode, we will use mgmt AAD token # instead of Batch AAD token to auth if in_cloud_console(): resource = cli_ctx.cloud.endpoints.active_directory_resource_id else: resource = cli_ctx.cloud.endpoints.batch_resource_id credentials, _, _ = profile.get_login_credentials(resource=resource) else: credentials = batchauth.SharedKeyCredentials(account_name, account_key) if not account_endpoint.startswith('https://'): account_endpoint = 'https://' + account_endpoint return batch.BatchServiceClient(credentials, base_url=account_endpoint)
def _get_mgmt_service_client(cli_ctx, client_type, subscription_bound=True, subscription_id=None, api_version=None, base_url_bound=True, resource=None, sdk_profile=None, **kwargs): from azure.cli.core._profile import Profile logger.debug('Getting management service client client_type=%s', client_type.__name__) resource = resource or cli_ctx.cloud.endpoints.active_directory_resource_id profile = Profile(cli_ctx=cli_ctx) cred, subscription_id, _ = profile.get_login_credentials(subscription_id=subscription_id, resource=resource) client_kwargs = {} if base_url_bound: client_kwargs = {'base_url': cli_ctx.cloud.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if sdk_profile: client_kwargs['profile'] = sdk_profile if kwargs: client_kwargs.update(kwargs) if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) configure_common_settings(cli_ctx, client) return client, subscription_id
def setup_continuous_delivery(self, resource_group_name, name, repo_url, branch, git_token, slot, cd_app_type_details, cd_project_url, cd_create_account, location, test, private_repo_username, private_repo_password, webapp_list): """ This method sets up CD for an Azure Web App thru Team Services """ # Gather information about the Azure connection profile = Profile() subscription = profile.get_subscription() user = profile.get_current_account_user() cred, _, _ = profile.get_login_credentials(subscription_id=None) cd_manager = ContinuousDeliveryManager(self._update_progress) # Generate an Azure token with the VSTS resource app id auth_token = profile.get_access_token_for_resource( user, None, cd_manager.get_vsts_app_id()) cd_manager.set_repository_info(repo_url, branch, git_token, private_repo_username, private_repo_password) cd_manager.set_azure_web_info(resource_group_name, name, cred, subscription['id'], subscription['name'], subscription['tenantId'], location) vsts_cd_status = cd_manager.setup_continuous_delivery( slot, cd_app_type_details, cd_project_url, cd_create_account, auth_token, test, webapp_list) return vsts_cd_status
def list_releases(name, resource_group_name): """ Lists all the release definitions that are deployed to a given Azure container service. :param name: Name of the target Azure container service instance. :type name: String :param resource_group_name: Name of Azure container service's resource group. :type resource_group_name: String """ profile = Profile() cred, subscription_id, _ = profile.get_login_credentials() o_auth_token = cred.signed_session().headers['Authorization'] o_auth_token.replace(" ", "%20") get_releases_action = '/configureCI/1/releases?api-version={version}&token={o_auth_token}' get_releases_url = RP_URL.format( subscription_id=subscription_id, resource_group_name=resource_group_name, container_service_name=name) + get_releases_action.format( version=API_VERSION, o_auth_token=o_auth_token) headers = {'Content-type': 'application/json', 'Authorization': o_auth_token} req = requests.get(get_releases_url, headers=headers, timeout=600) if req.status_code != 200: raise CLIError( 'Server returned status code: ' + str(req.status_code) + '. Could not list releases: ' + req.text) json_request = req.json() return json_request
def test_get_login_credentials(self, mock_get_token, mock_read_cred_file): some_token_type = 'Bearer' mock_read_cred_file.return_value = [Test_Profile.token_entry1] mock_get_token.return_value = (some_token_type, Test_Profile.raw_token1) #setup storage_mock = {'subscriptions': None} profile = Profile(storage_mock) consolidated = Profile._normalize_properties(self.user1, [self.subscription1], False, ENV_DEFAULT) profile._set_subscriptions(consolidated) #action cred, subscription_id, _ = profile.get_login_credentials() #verify self.assertEqual(subscription_id, '1') #verify the cred._tokenRetriever is a working lambda token_type, token = cred._token_retriever() self.assertEqual(token, self.raw_token1) self.assertEqual(some_token_type, token_type) self.assertEqual(mock_read_cred_file.call_count, 1) mock_get_token.assert_called_once_with(mock.ANY, self.user1, self.tenant_id, 'https://management.core.windows.net/') self.assertEqual(mock_get_token.call_count, 1)
def _get_and_write_certificate(cmd, public_key_file, cert_file, ssh_client_folder): cloudtoscope = { "azurecloud": "https://pas.windows.net/CheckMyAccess/Linux/.default", "azurechinacloud": "https://pas.chinacloudapi.cn/CheckMyAccess/Linux/.default", "azureusgovernment": "https://pasff.usgovcloudapi.net/CheckMyAccess/Linux/.default" } scope = cloudtoscope.get(cmd.cli_ctx.cloud.name.lower(), None) if not scope: raise azclierror.InvalidArgumentValueError( f"Unsupported cloud {cmd.cli_ctx.cloud.name.lower()}", "Supported clouds include azurecloud,azurechinacloud,azureusgovernment") scopes = [scope] data = _prepare_jwk_data(public_key_file) from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cmd.cli_ctx) # We currently are using the presence of get_msal_token to detect if we are running on an older azure cli client # TODO: Remove when adal has been deprecated for a while if hasattr(profile, "get_msal_token"): # we used to use the username from the token but now we throw it away _, certificate = profile.get_msal_token(scopes, data) else: credential, _, _ = profile.get_login_credentials(subscription_id=profile.get_subscription()["id"]) certificatedata = credential.get_token(*scopes, data=data) certificate = certificatedata.token if not cert_file: cert_file = public_key_file + "-aadcert.pub" logger.debug("Generating certificate %s", cert_file) _write_cert_file(certificate, cert_file) # instead we use the validprincipals from the cert due to mismatched upn and email in guest scenarios username = ssh_utils.get_ssh_cert_principals(cert_file, ssh_client_folder)[0] return cert_file, username.lower()
def _update_sp(cmd, graph_client, aad_sp, ams, account_name, resource_group_name, display_name, new_sp_name, role, years, sp_password, xml): profile = Profile(cli_ctx=cmd.cli_ctx) _, _, tenant_id = profile.get_login_credentials( resource=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id ) sp_oid = aad_sp.object_id app_id = aad_sp.app_id app_object_id = _get_application_object_id(graph_client.applications, app_id) subscription_id = get_subscription_id(cmd.cli_ctx) if sp_password or years: raise CLIError( "To update the credentials please use the reset-credentials command." ) if new_sp_name: display_name = new_sp_name.replace('http://', '') update_application(graph_client.applications, app_object_id, display_name) if role: _assign_role(cmd, role, sp_oid, ams.id) return _build_sp_result(subscription_id, ams.location, resource_group_name, account_name, tenant_id, app_id, display_name, sp_password, cmd.cli_ctx.cloud.endpoints.management, cmd.cli_ctx.cloud.endpoints.active_directory, cmd.cli_ctx.cloud.endpoints.resource_manager, role, xml)
def reset_sp_credentials_for_mediaservice(cmd, client, account_name, resource_group_name, sp_name=None, role='Contributor', sp_password=None, xml=False, years=None): ams = client.get(resource_group_name, account_name) graph_client = _graph_client_factory(cmd.cli_ctx) sp_name = _create_sp_name(account_name, sp_name) if sp_name is None else sp_name sp_password = _create_sp_password(sp_password) app_display_name = sp_name.replace('http://', '') aad_sp = _get_service_principal(graph_client, sp_name) if not aad_sp: raise CLIError("Can't find a service principal matching '{}'".format(app_display_name)) profile = Profile(cli_ctx=cmd.cli_ctx) _, _, tenant_id = profile.get_login_credentials( resource=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id) sp_oid = aad_sp.object_id app_id = aad_sp.app_id subscription_id = get_subscription_id(cmd.cli_ctx) app_object_id = _get_application_object_id(graph_client.applications, app_id) _update_password_credentials(graph_client, app_object_id, sp_password, years) _assign_role(cmd, role, sp_oid, ams.id) return _build_sp_result(subscription_id, ams.location, resource_group_name, account_name, tenant_id, app_id, app_display_name, sp_password, cmd.cli_ctx.cloud.endpoints.management, cmd.cli_ctx.cloud.endpoints.active_directory, cmd.cli_ctx.cloud.endpoints.resource_manager, role, xml)
def cf_attestation_data(cli_ctx, *_): from ..vendored_sdks.azure_attestation import AttestationClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource="https://attest.azure.net") return AttestationClient(credentials=cred)
def loganalytics_data_plane_client(cli_ctx, _): """Initialize Log Analytics data client for use with CLI.""" from .vendored_sdks.loganalytics import LogAnalyticsDataClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource="https://api.loganalytics.io") return LogAnalyticsDataClient(cred)
def applicationinsights_mgmt_plane_client(cli_ctx, _, subscription=None): """Initialize Log Analytics mgmt client for use with CLI.""" from .vendored_sdks.mgmt_applicationinsights import ApplicationInsightsManagementClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) # Use subscription from resource_id where possible, otherwise use login. if subscription: cred, _, _ = profile.get_login_credentials(subscription_id=subscription) return ApplicationInsightsManagementClient( cred, subscription ) cred, sub_id, _ = profile.get_login_credentials() return ApplicationInsightsManagementClient( cred, sub_id )
def cf_datalake_store_filesystem(account_name): profile = Profile() subscription_id = None cred, subscription_id, _ = profile.get_login_credentials(subscription_id=subscription_id) return core.AzureDLFileSystem( token=cred, store_name=account_name, url_suffix=CLOUD.suffixes.azure_datalake_store_file_system_endpoint)
def cf_log_analytics_data_plane(cli_ctx, _): """Initialize Log Analytics data client for use with CLI.""" from azure.loganalytics import LogAnalyticsDataClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource="https://api.loganalytics.io") return LogAnalyticsDataClient(cred)
def _graph_client_factory(**_): from azure.cli.core._profile import Profile profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=get_env()[ENDPOINT_URLS.ACTIVE_DIRECTORY_GRAPH_RESOURCE_ID]) client = GraphRbacManagementClient(cred, tenant_id) configure_common_settings(client) return client
def applicationinsights_data_plane_client(cli_ctx, _, subscription=None): """Initialize Log Analytics data client for use with CLI.""" from .vendored_sdks.applicationinsights import ApplicationInsightsDataClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource=cli_ctx.cloud.endpoints.app_insights_resource_id, subscription_id=subscription) return ApplicationInsightsDataClient(cred)
def synapse_data_plane_factory(cli_ctx, _, subscription=None): from azext_synapse.vendored_sdks.azure_synapse import SynapseClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource="https://dev.azuresynapse.net", subscription_id=subscription) return SynapseClient(synapse_dns_suffix='dev.azuresynapse.net', livy_api_version='2019-11-01-preview', credentials=cred)
def _get_mgmt_service_client(cli_ctx, client_type, subscription_bound=True, subscription_id=None, api_version=None, base_url_bound=True, resource=None, sdk_profile=None, aux_subscriptions=None, aux_tenants=None, **kwargs): from azure.cli.core._profile import Profile from azure.cli.core.util import resource_to_scopes logger.debug('Getting management service client client_type=%s', client_type.__name__) resource = resource or cli_ctx.cloud.endpoints.active_directory_resource_id profile = Profile(cli_ctx=cli_ctx) cred, subscription_id, _ = profile.get_login_credentials( subscription_id=subscription_id, resource=resource, aux_subscriptions=aux_subscriptions, aux_tenants=aux_tenants) client_kwargs = {} if base_url_bound: client_kwargs = {'base_url': cli_ctx.cloud.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if sdk_profile: client_kwargs['profile'] = sdk_profile if kwargs: client_kwargs.update(kwargs) if is_track2(client_type): client_kwargs.update(_prepare_client_kwargs_track2(cli_ctx)) client_kwargs['credential_scopes'] = resource_to_scopes(resource) # Track 2 currently lacks the ability to take external credentials. # https://github.com/Azure/azure-sdk-for-python/issues/8313 # As a temporary workaround, manually add external tokens to 'x-ms-authorization-auxiliary' header. # https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant if getattr(cred, "_external_tenant_token_retriever", None): *_, external_tenant_tokens = cred.get_all_tokens( *resource_to_scopes(resource)) # Hard-code scheme to 'Bearer' as _BearerTokenCredentialPolicyBase._update_headers does. client_kwargs['headers']['x-ms-authorization-auxiliary'] = \ ', '.join("Bearer {}".format(t[1]) for t in external_tenant_tokens) if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) if not is_track2(client): configure_common_settings(cli_ctx, client) return client, subscription_id
def create_keyvault( client, resource_group_name, vault_name, location, #pylint:disable=too-many-arguments sku=SkuName.standard.value, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, no_self_perms=False, tags=None): from azure.cli.core._profile import Profile profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=get_env()[ENDPOINT_URLS.ACTIVE_DIRECTORY_GRAPH_RESOURCE_ID]) graph_client = GraphRbacManagementClient(cred, tenant_id) subscription = profile.get_subscription() if no_self_perms: access_policies = [] else: permissions = Permissions(keys=[ KeyPermissions.get, KeyPermissions.create, KeyPermissions.delete, KeyPermissions.list, KeyPermissions.update, KeyPermissions.import_enum, KeyPermissions.backup, KeyPermissions.restore ], secrets=[SecretPermissions.all], certificates=[CertificatePermissions.all]) object_id = _get_current_user_object_id(graph_client) if not object_id: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError('Cannot create vault.\n' 'Unable to query active directory for information '\ 'about the current user.\n' 'You may try the --no-self-perms flag to create a vault'\ ' without permissions.') access_policies = [ AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions) ] properties = VaultProperties( tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment) parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)
def create_keyvault(client, resource_group_name, vault_name, location=None, #pylint:disable=too-many-arguments sku=SkuName.standard.value, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, no_self_perms=None, tags=None): from azure.mgmt.keyvault.models import VaultCreateOrUpdateParameters from azure.cli.core._profile import Profile, CLOUD from azure.graphrbac.models import GraphErrorException profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient(cred, tenant_id, base_url=CLOUD.endpoints.active_directory_graph_resource_id) # pylint: disable=line-too-long subscription = profile.get_subscription() if no_self_perms: access_policies = [] else: permissions = Permissions(keys=[KeyPermissions.get, KeyPermissions.create, KeyPermissions.delete, KeyPermissions.list, KeyPermissions.update, KeyPermissions.import_enum, KeyPermissions.backup, KeyPermissions.restore], secrets=[SecretPermissions.all], certificates=[CertificatePermissions.all]) try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError('Cannot create vault.\n' 'Unable to query active directory for information '\ 'about the current user.\n' 'You may try the --no-self-perms flag to create a vault'\ ' without permissions.') access_policies = [AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions)] properties = VaultProperties(tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment) parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)
def _graph_client_factory(cli_ctx, **_): profile = Profile(cli_ctx=cli_ctx) cred, _, tenant_id = profile.get_login_credentials( resource=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) client = GraphRbacManagementClient( cred, tenant_id, base_url=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) configure_common_settings(cli_ctx, client) return client
def applicationinsights_data_plane_client(cli_ctx, _, subscription=None): """Initialize Log Analytics data client for use with CLI.""" from .vendored_sdks.applicationinsights import ApplicationInsightsDataClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource="https://api.applicationinsights.io", subscription_id=subscription ) return ApplicationInsightsDataClient(cred)
def create_keyvault( client, resource_group_name, vault_name, location, #pylint:disable=too-many-arguments sku=SkuName.standard.value, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, no_self_perms=False, tags=None): from azure.cli.core._profile import Profile profile = Profile() cred, _, tenant_id = profile.get_login_credentials(for_graph_client=True) graph_client = GraphRbacManagementClient(cred, tenant_id) subscription = profile.get_subscription() if no_self_perms: access_policies = [] else: # TODO Use the enums instead of strings when new keyvault SDK is released # https://github.com/Azure/azure-sdk-for-python/blob/dev/azure-mgmt-keyvault/ # azure/mgmt/keyvault/models/key_vault_management_client_enums.py permissions = Permissions(keys=[ 'get', 'create', 'delete', 'list', 'update', 'import', 'backup', 'restore' ], secrets=['all']) object_id = _get_current_user_object_id(graph_client) if not object_id: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError('Cannot create vault.\n' 'Unable to query active directory for information '\ 'about the current user.\n' 'You may try the --no-self-perms flag to create a vault'\ ' without permissions.') access_policies = [ AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions) ] properties = VaultProperties( tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment) parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)
def validate_member_id(namespace): from azure.cli.core._profile import Profile, CLOUD try: uuid.UUID(namespace.url) profile = Profile() _, _, tenant_id = profile.get_login_credentials() graph_url = CLOUD.endpoints.active_directory_graph_resource_id namespace.url = '{}{}/directoryObjects/{}'.format(graph_url, tenant_id, namespace.url) except ValueError: pass # let it go, invalid values will be caught by server anyway
def cf_dls_filesystem(account_name): from azure.datalake.store import core profile = Profile() subscription_id = None cred, subscription_id, _ = profile.get_login_credentials( subscription_id=subscription_id, resource=CLOUD.endpoints.active_directory_data_lake_resource_id) return core.AzureDLFileSystem( token=cred, store_name=account_name, url_suffix=CLOUD.suffixes.azure_datalake_store_file_system_endpoint)
def _graph_client_factory(cli_ctx, **_): from azure.cli.core._profile import Profile from azure.cli.core.commands.client_factory import configure_common_settings from azure.graphrbac import GraphRbacManagementClient profile = Profile(cli_ctx=cli_ctx) cred, _, tenant_id = profile.get_login_credentials( resource=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) client = GraphRbacManagementClient(cred, tenant_id, base_url=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) configure_common_settings(cli_ctx, client) return client
def _get_mgmt_service_client(client_type, subscription_bound=True, subscription_id=None): logger.info('Getting management service client client_type=%s', client_type.__name__) profile = Profile() cred, subscription_id, _ = profile.get_login_credentials(subscription_id=subscription_id) if subscription_bound: client = client_type(cred, subscription_id) else: client = client_type(cred) configure_common_settings(client) return (client, subscription_id)
def _object_id_args_helper(object_id, spn, upn): if not object_id: from azure.cli.core._profile import Profile, CLOUD profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient(cred, tenant_id, base_url=CLOUD.endpoints.active_directory_graph_resource_id) object_id = _get_object_id(graph_client, spn=spn, upn=upn) if not object_id: raise CLIError('Unable to get object id from principal name.') return object_id
def _get_owner_object_id(): from azure.cli.core._profile import Profile, CLOUD from azure.graphrbac.models import GraphErrorException profile = Profile() cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient(cred, tenant_id, base_url=CLOUD.endpoints.active_directory_graph_resource_id) subscription = profile.get_subscription() try: return _get_current_user_object_id(graph_client) except GraphErrorException: return _get_object_id(graph_client, subscription=subscription)
def recover_keyvault(client, vault_name, resource_group_name, location): from azure.mgmt.keyvault.models import VaultCreateOrUpdateParameters, CreateMode from azure.cli.core._profile import Profile, CLOUD profile = Profile() _, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_graph_resource_id) params = VaultCreateOrUpdateParameters(location, properties={'tenant_id': tenant_id, 'sku': Sku(name=SkuName.standard.value), 'create_mode': CreateMode.recover.value}) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=params)
def _get_mgmt_service_client(client_type, subscription_bound=True, subscription_id=None, api_version=None): logger.info('Getting management service client client_type=%s', client_type.__name__) profile = Profile() cred, subscription_id, _ = profile.get_login_credentials(subscription_id=subscription_id) client_kwargs = {'base_url': CLOUD.endpoints.resource_manager} if api_version: client_kwargs['api_version'] = api_version if subscription_bound: client = client_type(cred, subscription_id, **client_kwargs) else: client = client_type(cred, **client_kwargs) configure_common_settings(client) return (client, subscription_id)
def _mock_get_mgmt_service_client(client_type, subscription_bound=True, subscription_id=None, api_version=None): # version of _get_mgmt_service_client to use when recording or playing tests profile = Profile() cred, subscription_id, _ = profile.get_login_credentials(subscription_id=subscription_id) if subscription_bound: client = client_type(cred, subscription_id, api_version=api_version) \ if api_version else client_type(cred, subscription_id) else: client = client_type(cred, api_version=api_version) \ if api_version else client_type(cred) client = _debug.allow_debug_connection(client) client.config.add_user_agent("AZURECLI/TEST/{}".format(core_version)) return (client, subscription_id)
def test_get_login_credentials_for_graph_client(self, mock_get_token, mock_read_cred_file): some_token_type = 'Bearer' mock_read_cred_file.return_value = [Test_Profile.token_entry1] mock_get_token.return_value = (some_token_type, Test_Profile.raw_token1) #setup storage_mock = {'subscriptions': None} profile = Profile(storage_mock) consolidated = Profile._normalize_properties(self.user1, [self.subscription1], False, ENV_DEFAULT) profile._set_subscriptions(consolidated) #action cred, _, tenant_id = profile.get_login_credentials(for_graph_client=True) _, _ = cred._token_retriever() #verify mock_get_token.assert_called_once_with(mock.ANY, self.user1, self.tenant_id, 'https://graph.windows.net/') self.assertEqual(tenant_id, self.tenant_id)
def batch_data_service_factory(kwargs): import azure.batch.batch_service_client as batch import azure.batch.batch_auth as batchauth account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) account_endpoint = kwargs.pop('account_endpoint', None) kwargs.pop('yes', None) credentials = None if not account_key: from azure.cli.core._profile import Profile, CLOUD profile = Profile() credentials, _, _ = profile.get_login_credentials( resource=CLOUD.endpoints.batch_resource_id) else: credentials = batchauth.SharedKeyCredentials(account_name, account_key) return batch.BatchServiceClient(credentials, base_url=account_endpoint)
def test_get_login_credentials_for_data_lake_client(self, mock_get_token, mock_read_cred_file): some_token_type = 'Bearer' mock_read_cred_file.return_value = [Test_Profile.token_entry1] mock_get_token.return_value = (some_token_type, Test_Profile.raw_token1) # setup storage_mock = {'subscriptions': None} profile = Profile(storage_mock, use_global_creds_cache=False) consolidated = Profile._normalize_properties(self.user1, [self.subscription1], False) profile._set_subscriptions(consolidated) # action cred, _, tenant_id = profile.get_login_credentials( resource=CLOUD.endpoints.active_directory_data_lake_resource_id) _, _ = cred._token_retriever() # verify mock_get_token.assert_called_once_with(mock.ANY, self.user1, self.tenant_id, 'https://datalake.azure.net/') self.assertEqual(tenant_id, self.tenant_id)
def batch_data_service_factory(cli_ctx, kwargs): import azure.batch.batch_service_client as batch import azure.batch.batch_auth as batchauth account_name = kwargs.pop('account_name', None) account_key = kwargs.pop('account_key', None) account_endpoint = kwargs.pop('account_endpoint', None) kwargs.pop('yes', None) credentials = None if not account_key: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) credentials, _, _ = profile.get_login_credentials( resource=cli_ctx.cloud.endpoints.batch_resource_id) else: credentials = batchauth.SharedKeyCredentials(account_name, account_key) if not account_endpoint.startswith('https://'): account_endpoint = 'https://' + account_endpoint return batch.BatchServiceClient(credentials, base_url=account_endpoint)
def recover_keyvault(cmd, client, vault_name, resource_group_name, location): from azure.cli.core._profile import Profile VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters', resource_type=ResourceType.MGMT_KEYVAULT) CreateMode = cmd.get_models('CreateMode', resource_type=ResourceType.MGMT_KEYVAULT) Sku = cmd.get_models('Sku', resource_type=ResourceType.MGMT_KEYVAULT) SkuName = cmd.get_models('SkuName', resource_type=ResourceType.MGMT_KEYVAULT) profile = Profile(cli_ctx=cmd.cli_ctx) _, _, tenant_id = profile.get_login_credentials( resource=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id) params = VaultCreateOrUpdateParameters(location=location, properties={'tenant_id': tenant_id, 'sku': Sku(name=SkuName.standard.value), 'create_mode': CreateMode.recover.value}) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=params)
def __init__(self, cli_ctx): profile = Profile(cli_ctx=cli_ctx) self._creds, _, _ = profile.get_login_credentials(subscription_id=None)
def get_subscription_id(): profile = Profile() _, subscription_id, _ = profile.get_login_credentials() return subscription_id
def create_keyvault(cmd, client, # pylint: disable=too-many-locals resource_group_name, vault_name, location=None, sku=None, enabled_for_deployment=None, enabled_for_disk_encryption=None, enabled_for_template_deployment=None, enable_soft_delete=None, enable_purge_protection=None, bypass=None, default_action=None, no_self_perms=None, tags=None): from azure.cli.core._profile import Profile from azure.graphrbac.models import GraphErrorException from azure.graphrbac import GraphRbacManagementClient VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters', resource_type=ResourceType.MGMT_KEYVAULT) Permissions = cmd.get_models('Permissions', resource_type=ResourceType.MGMT_KEYVAULT) KeyPermissions = cmd.get_models('KeyPermissions', resource_type=ResourceType.MGMT_KEYVAULT) SecretPermissions = cmd.get_models('SecretPermissions', resource_type=ResourceType.MGMT_KEYVAULT) CertificatePermissions = cmd.get_models('CertificatePermissions', resource_type=ResourceType.MGMT_KEYVAULT) StoragePermissions = cmd.get_models('StoragePermissions', resource_type=ResourceType.MGMT_KEYVAULT) AccessPolicyEntry = cmd.get_models('AccessPolicyEntry', resource_type=ResourceType.MGMT_KEYVAULT) Sku = cmd.get_models('Sku', resource_type=ResourceType.MGMT_KEYVAULT) VaultProperties = cmd.get_models('VaultProperties', resource_type=ResourceType.MGMT_KEYVAULT) profile = Profile(cli_ctx=cmd.cli_ctx) cred, _, tenant_id = profile.get_login_credentials( resource=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient( cred, tenant_id, base_url=cmd.cli_ctx.cloud.endpoints.active_directory_graph_resource_id) subscription = profile.get_subscription() # if bypass or default_action was specified create a NetworkRuleSet # if neither were specified we make network_acls None if cmd.supported_api_version(resource_type=ResourceType.MGMT_KEYVAULT, min_api='2018-02-14'): network_acls = _create_network_rule_set(cmd, bypass, default_action) if bypass or default_action else None if no_self_perms: access_policies = [] else: permissions = Permissions(keys=[KeyPermissions.get, KeyPermissions.create, KeyPermissions.delete, KeyPermissions.list, KeyPermissions.update, KeyPermissions.import_enum, KeyPermissions.backup, KeyPermissions.restore, KeyPermissions.recover], secrets=[ SecretPermissions.get, SecretPermissions.list, SecretPermissions.set, SecretPermissions.delete, SecretPermissions.backup, SecretPermissions.restore, SecretPermissions.recover], certificates=[ CertificatePermissions.get, CertificatePermissions.list, CertificatePermissions.delete, CertificatePermissions.create, CertificatePermissions.import_enum, CertificatePermissions.update, CertificatePermissions.managecontacts, CertificatePermissions.getissuers, CertificatePermissions.listissuers, CertificatePermissions.setissuers, CertificatePermissions.deleteissuers, CertificatePermissions.manageissuers, CertificatePermissions.recover], storage=[ StoragePermissions.get, StoragePermissions.list, StoragePermissions.delete, StoragePermissions.set, StoragePermissions.update, StoragePermissions.regeneratekey, StoragePermissions.setsas, StoragePermissions.listsas, StoragePermissions.getsas, StoragePermissions.deletesas]) try: object_id = _get_current_user_object_id(graph_client) except GraphErrorException: object_id = _get_object_id(graph_client, subscription=subscription) if not object_id: raise CLIError('Cannot create vault.\nUnable to query active directory for information ' 'about the current user.\nYou may try the --no-self-perms flag to ' 'create a vault without permissions.') access_policies = [AccessPolicyEntry(tenant_id=tenant_id, object_id=object_id, permissions=permissions)] properties = VaultProperties(tenant_id=tenant_id, sku=Sku(name=sku), access_policies=access_policies, vault_uri=None, enabled_for_deployment=enabled_for_deployment, enabled_for_disk_encryption=enabled_for_disk_encryption, enabled_for_template_deployment=enabled_for_template_deployment, enable_soft_delete=enable_soft_delete, enable_purge_protection=enable_purge_protection) if hasattr(properties, 'network_acls'): properties.network_acls = network_acls parameters = VaultCreateOrUpdateParameters(location=location, tags=tags, properties=properties) return client.create_or_update(resource_group_name=resource_group_name, vault_name=vault_name, parameters=parameters)