def list_subs(self, line): from azure.cli.core._profile import Profile try: from azure.cli.core.util import CLIError except ImportError: from azure.cli.core._util import CLIError self._redirect_logging('az.azure.cli.core._profile') # load cached credentials in Profile() object profile = Profile() try: # if user is logged in, get their current subscription profile.get_subscription() except CLIError: # otherwise interactively prompy user to log in profile.find_subscriptions_on_login(True, None, None, None, None) # list all subscriptions subs = profile.load_cached_subscriptions() if not subs: print('No subscriptions available.') print('Please run `az login` from the console then try again') return print("Available subscriptions:\n {}".format('\n '.join( [sub['name'] for sub in subs])))
def select_sub(self, line): from azure.cli.core._profile import Profile try: from azure.cli.core.util import CLIError except ImportError: from azure.cli.core._util import CLIError self._redirect_logging('az.azure.cli.core._profile') p = argparse.ArgumentParser() p.add_argument('subscription') parsed_args = p.parse_args(shlex.split(line)) # if user is already logged in, get their subscriptions profile = Profile() subs = profile.load_cached_subscriptions() if not subs: # user not logged in--prompt them profile.find_subscriptions_on_login(True, None, None, None, None) try: profile.set_active_subscription(parsed_args.subscription) print('Active subscription set to {}'.format( profile.get_subscription()['name'])) except CLIError as exc: print(exc) print('Active subscription remains {}'.format( profile.get_subscription()['name']))
def create_bot_json(cmd, client, resource_group_name, resource_name, app_password=None, raw_bot_properties=None): if not raw_bot_properties: raw_bot_properties = client.bots.get( resource_group_name=resource_group_name, resource_name=resource_name ) if not app_password: site_name = get_bot_site_name(raw_bot_properties.properties.endpoint) app_settings = get_app_settings( cmd=cmd, resource_group_name=resource_group_name, name=site_name ) app_password = [item['value'] for item in app_settings if item['name'] == 'MicrosoftAppPassword'][0] profile = Profile(cli_ctx=cmd.cli_ctx) return { 'type': 'abs', 'id': raw_bot_properties.name, 'name': raw_bot_properties.properties.display_name, 'appId': raw_bot_properties.properties.msa_app_id, 'appPassword': app_password, 'endpoint': raw_bot_properties.properties.endpoint, 'resourceGroup': str(resource_group_name), 'tenantId': profile.get_subscription(subscription=client.config.subscription_id)['tenantId'], 'subscriptionId': client.config.subscription_id }
def get_current_subscription(): try: profile = Profile(cli_ctx=cli_ctx) return profile.get_subscription()[_SUBSCRIPTION_NAME] except CLIError: return None # Not logged in return None # Not logged in
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 _get_tenant_id(): ''' Gets tenantId from current subscription. ''' profile = Profile() sub = profile.get_subscription() return sub['tenantId']
def get_resource_by_name(cli_ctx, resource_name, resource_type): """Returns the ARM resource in the current subscription with resource_name. :param str resource_name: The name of resource :param str resource_type: The type of resource """ result = get_resources_in_subscription(cli_ctx, resource_type) elements = [item for item in result if item.name.lower() == resource_name.lower()] if not elements: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) message = "The resource with name '{}' and type '{}' could not be found".format( resource_name, resource_type) try: subscription = profile.get_subscription( cli_ctx.data['subscription_id']) raise CLIError( "{} in subscription '{} ({})'.".format(message, subscription['name'], subscription['id'])) except (KeyError, TypeError): raise CLIError( "{} in the current subscription.".format(message)) elif len(elements) == 1: return elements[0] else: raise CLIError( "More than one resources with type '{}' are found with name '{}'.".format( resource_type, resource_name))
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 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 _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 _arm_get_resource_by_name(cli_ctx, resource_name, resource_type): """Returns the ARM resource in the current subscription with resource_name. :param str resource_name: The name of resource :param str resource_type: The type of resource """ result = get_resources_in_subscription(cli_ctx, resource_type) elements = [item for item in result if item.name.lower() == resource_name.lower()] if not elements: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) message = "The resource with name '{}' and type '{}' could not be found".format( resource_name, resource_type) try: subscription = profile.get_subscription() raise CLIError("{} in subscription '{} ({})'.".format(message, subscription['name'], subscription['id'])) except (KeyError, TypeError): raise CLIError("{} in the current subscription.".format(message)) elif len(elements) == 1: return elements[0] else: raise CLIError( "More than one resources with type '{}' are found with name '{}'.".format( resource_type, resource_name))
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 create_bot_json(cmd, client, resource_group_name, resource_name, app_password=None, raw_bot_properties=None): if not raw_bot_properties: raw_bot_properties = client.bots.get( resource_group_name=resource_group_name, resource_name=resource_name ) if not app_password: app_settings = get_app_settings( cmd=cmd, resource_group_name=resource_group_name, name=resource_name ) app_password = [item['value'] for item in app_settings if item['name'] == 'MicrosoftAppPassword'][0] profile = Profile(cli_ctx=cmd.cli_ctx) return { 'type': 'abs', 'id': raw_bot_properties.name, 'name': raw_bot_properties.properties.display_name, 'appId': raw_bot_properties.properties.msa_app_id, 'appPassword': app_password, 'endpoint': raw_bot_properties.properties.endpoint, 'resourceGroup': str(resource_group_name), 'tenantId': profile.get_subscription(subscription=client.config.subscription_id)['tenantId'], 'subscriptionId': client.config.subscription_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 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 show_subscription(subscription=None, expanded_view=None): profile = Profile() if not expanded_view: return profile.get_subscription(subscription) logger.warning("'--expanded-view' is deprecating and will be removed in a future release. You can get the same " "information using 'az cloud show'") return profile.get_expanded_subscription_info(subscription)
def show_subscription(subscription=None, show_auth_for_sdk=None): import json profile = Profile() if not show_auth_for_sdk: return profile.get_subscription(subscription) # sdk-auth file should be in json format all the time, hence the print print(json.dumps(profile.get_sp_auth_info(subscription), indent=2))
def test_get_subscription(self): 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) self.assertEqual(self.display_name1, profile.get_subscription()['name']) self.assertEqual(self.display_name1, profile.get_subscription(subscription=self.display_name1)['name']) sub_id = self.id1.split('/')[-1] self.assertEqual(sub_id, profile.get_subscription()['id']) self.assertEqual(sub_id, profile.get_subscription(subscription=sub_id)['id']) self.assertRaises(CLIError, profile.get_subscription, "random_id")
def show_subscription(cmd, subscription=None, show_auth_for_sdk=None): import json profile = Profile(cli_ctx=cmd.cli_ctx) if not show_auth_for_sdk: return profile.get_subscription(subscription) # sdk-auth file should be in json format all the time, hence the print print(json.dumps(profile.get_sp_auth_info(subscription), indent=2))
def test_get_subscription(self): storage_mock = {'subscriptions': None} profile = Profile(storage_mock) consolidated = Profile._normalize_properties(self.user1, [self.subscription1], False) profile._set_subscriptions(consolidated) self.assertEqual(self.display_name1, profile.get_subscription()['name']) self.assertEqual(self.display_name1, profile.get_subscription(subscription=self.display_name1)['name']) sub_id = self.id1.split('/')[-1] self.assertEqual(sub_id, profile.get_subscription()['id']) self.assertEqual(sub_id, profile.get_subscription(subscription=sub_id)['id']) self.assertRaises(CLIError, profile.get_subscription, "random_id")
def server_ad_admin_set(client, resource_group_name, server_name, **kwargs): profile = Profile() sub = profile.get_subscription() kwargs['tenant_id'] = sub['tenantId'] return client.create_or_update(server_name=server_name, resource_group_name=resource_group_name, properties=kwargs)
def show_subscription(subscription=None, expanded_view=None): profile = Profile() if not expanded_view: return profile.get_subscription(subscription) logger.warning( "'--expanded-view' is deprecating and will be removed in a future release. You can get the same " "information using 'az cloud show'") return profile.get_expanded_subscription_info(subscription)
def _create_scope(): # Gets tenantId from current subscription. from azure.cli.core._profile import Profile profile = Profile() sub = profile.get_subscription() tenant_id = sub['tenantId'] scope_format_string = '/providers/Microsoft.Management/managementGroups/{}' return scope_format_string.format(tenant_id)
def _get_tenant_id(): ''' Gets tenantId from current subscription. ''' from azure.cli.core._profile import Profile profile = Profile() sub = profile.get_subscription() return sub['tenantId']
def get_auth_header(cmd): from azure.cli.core._profile import Profile from ._constants import CLIENT_ID profile = Profile(cli_ctx=cmd.cli_ctx) account = profile.get_subscription() access_token = profile.get_access_token_for_resource( account['user']['name'], account['tenantId'], CLIENT_ID) return {'Authorization': '{}'.format('Bearer ' + access_token)}
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 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 list_subs(self, line): from azure.cli.core._profile import Profile try: from azure.cli.core.util import CLIError except ImportError: from azure.cli.core._util import CLIError self._redirect_logging('az.azure.cli.core._profile') profile = Profile() try: profile.get_subscription() except CLIError: profile.find_subscriptions_on_login(True, None, None, None, None) subs = profile.load_cached_subscriptions() if not subs: print('No subscriptions available.') print('Please run `az login` from the console then try again') return print("Available subscriptions:\n {}".format('\n '.join( [sub['name'] for sub in subs])))
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 _get_service_token(): profile = Profile() credsCache = CredsCache() account = profile.get_subscription() user_name = account['user']['name'] tenant = account['tenantId'] scheme, token = credsCache.retrieve_token_for_user(user_name, tenant, SERVICE_RESOURCE_ID) service_token = "{} {}".format(scheme, token) return service_token
def show_subscription(cmd, subscription=None, show_auth_for_sdk=None): import json profile = Profile(cli_ctx=cmd.cli_ctx) if show_auth_for_sdk: from azure.cli.command_modules.role.custom import CREDENTIAL_WARNING logger.warning(CREDENTIAL_WARNING) # sdk-auth file should be in json format all the time, hence the print print(json.dumps(profile.get_sp_auth_info(subscription), indent=2)) return return profile.get_subscription(subscription)
def server_ad_admin_set( client, resource_group_name, server_name, **kwargs): profile = Profile() sub = profile.get_subscription() kwargs['tenant_id'] = sub['tenantId'] return client.create_or_update( server_name=server_name, resource_group_name=resource_group_name, properties=kwargs)
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 fetch_and_post_at_to_csp(cmd, api_server_port, tenantId, kid, clientproxy_process): req_cnfJSON = {"kid": kid, "xms_ksl": "sw"} req_cnf = base64.urlsafe_b64encode( json.dumps(req_cnfJSON).encode('utf-8')).decode('utf-8') # remove padding '=' character if req_cnf[len(req_cnf) - 1] == '=': req_cnf = req_cnf[:-1] token_data = {"token_type": "pop", "key_id": kid, "req_cnf": req_cnf} profile = Profile(cli_ctx=cmd.cli_ctx) try: credential, _, _ = profile.get_login_credentials( subscription_id=profile.get_subscription()["id"], resource=consts.KAP_1P_Server_App_Scope) accessToken = credential.get_token(consts.KAP_1P_Server_App_Scope, data=token_data) jwtToken = accessToken.token except Exception as e: telemetry.set_exception( exception=e, fault_type=consts.Post_AT_To_ClientProxy_Failed_Fault_Type, summary= 'Failed to fetch access token using the PoP public key sent by client proxy' ) close_subprocess_and_raise_cli_error( clientproxy_process, 'Failed to post access token to client proxy' + str(e)) jwtTokenData = { "accessToken": jwtToken, "serverId": consts.KAP_1P_Server_AppId, "tenantID": tenantId, "kid": kid } post_at_uri = f'https://localhost:{api_server_port}/identity/at' # Needed to prevent skip tls warning from printing to the console original_stderr = sys.stderr f = open(os.devnull, 'w') sys.stderr = f post_at_response = make_api_call_with_retries( post_at_uri, jwtTokenData, "post", False, consts.PublicKey_Export_Fault_Type, 'Failed to post access token to client proxy', "Failed to post access token to client proxy", clientproxy_process) sys.stderr = original_stderr return post_at_response
def _get_service_token(): profile = Profile() credsCache = CredsCache() account = profile.get_subscription() user_name = account['user']['name'] tenant = account['tenantId'] if account['user']['type'] == _SERVICE_PRINCIPAL: scheme, token = credsCache.retrieve_token_for_service_principal(user_name, SERVICE_RESOURCE_ID) else: scheme, token = credsCache.retrieve_token_for_user(user_name, tenant, SERVICE_RESOURCE_ID) service_token = "{} {}".format(scheme, token) return service_token
def _toolbar_info(self): sub_name = "" try: profile = Profile(cli_ctx=self.cli_ctx) sub_name = profile.get_subscription()[_SUBSCRIPTION_NAME] except CLIError: pass curr_cloud = "Cloud: {}".format(self.cli_ctx.cloud.name) tool_val = 'Subscription: {}'.format( sub_name) if sub_name else curr_cloud settings_items = [ " [F1]Layout", "[F2]Defaults", "[F3]Keys", "[Ctrl+D]Quit", tool_val ] return settings_items
def stack_hci_cluster_create(cmd, client, resource_group_name, cluster_name, aad_client_id, location=None, tags=None, aad_tenant_id=None): if not aad_tenant_id: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cmd.cli_ctx) aad_tenant_id = profile.get_subscription()['tenantId'] return client.create(resource_group_name=resource_group_name, cluster_name=cluster_name, tags=tags, location=location, aad_client_id=aad_client_id, aad_tenant_id=aad_tenant_id)
def _toolbar_info(self): sub_name = "" try: profile = Profile(cli_ctx=self.cli_ctx) sub_name = profile.get_subscription()[_SUBSCRIPTION_NAME] except CLIError: pass curr_cloud = "Cloud: {}".format(self.cli_ctx.cloud.name) tool_val = 'Subscription: {}'.format(sub_name) if sub_name else curr_cloud settings_items = [ " [F1]Layout", "[F2]Defaults", "[F3]Keys", "[Ctrl+D]Quit", tool_val ] return settings_items
def _set_active_subscription(cloud_name): from azure.cli.core._profile import (Profile, _ENVIRONMENT_NAME, _SUBSCRIPTION_ID, _STATE, _SUBSCRIPTION_NAME) profile = Profile() subscription_to_use = get_cloud_subscription(cloud_name) or \ next((s[_SUBSCRIPTION_ID] for s in profile.load_cached_subscriptions() # noqa if s[_STATE] == 'Enabled'), None) if subscription_to_use: try: profile.set_active_subscription(subscription_to_use) sub = profile.get_subscription(subscription_to_use) logger.warning("Active subscription switched to '%s (%s)'.", sub[_SUBSCRIPTION_NAME], sub[_SUBSCRIPTION_ID]) except CLIError as e: logger.warning(e) logger.warning("Unable to automatically switch the active subscription. " "Use 'az account set'.") else: logger.warning("Use 'az login' to log in to this cloud.") logger.warning("Use 'az account set' to set the active subscription.")
def stack_hci_cluster_create(cmd, client, resource_group_name, cluster_name, aad_client_id, location=None, tags=None, aad_tenant_id=None): if not aad_tenant_id: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cmd.cli_ctx) aad_tenant_id = profile.get_subscription()['tenantId'] from azext_stack_hci.vendored_sdks.azurestackhci.models._models import Cluster cluster = Cluster(aad_client_id=aad_client_id, aad_tenant_id=aad_tenant_id, tags=tags, location=location) return client.create(resource_group_name=resource_group_name, cluster_name=cluster_name, cluster=cluster)
def create_bot_json(cmd, client, resource_group_name, resource_name, logger, app_password=None, # pylint:disable=too-many-locals raw_bot_properties=None, password_only=True): """ :param cmd: :param client: :param resource_group_name: :param resource_name: :param logger: :param app_password: :param raw_bot_properties: :return: Dictionary """ if not raw_bot_properties: raw_bot_properties = client.bots.get( resource_group_name=resource_group_name, resource_name=resource_name ) # Initialize names bot_file and secret to capture botFilePath and botFileSecret values from the application's # settings. bot_file = None bot_file_secret = None profile = Profile(cli_ctx=cmd.cli_ctx) if not app_password: site_name = WebAppOperations.get_bot_site_name(raw_bot_properties.properties.endpoint) app_settings = WebAppOperations.get_app_settings( cmd=cmd, resource_group_name=resource_group_name, name=site_name ) app_password_values = [item['value'] for item in app_settings if item['name'] == 'MicrosoftAppPassword'] app_password = app_password_values[0] if app_password_values else None if not app_password: bot_file_values = [item['value'] for item in app_settings if item['name'] == 'botFilePath'] bot_file = bot_file_values[0] if bot_file_values else None bot_file_secret_values = [item['value'] for item in app_settings if item['name'] == 'botFileSecret'] bot_file_secret = bot_file_secret_values[0] if bot_file_secret_values else None if not bot_file and not app_password: bot_site_name = WebAppOperations.get_bot_site_name(raw_bot_properties.properties.endpoint) scm_url = WebAppOperations.get_scm_url(cmd, resource_group_name, bot_site_name, None) # TODO: Reevaluate "Public-or-Gov" Azure logic. is_public_azure = ('azurewebsites.net' in raw_bot_properties.properties.endpoint or '.net' in raw_bot_properties.properties.endpoint or '.com' in raw_bot_properties.properties.endpoint) host = 'https://portal.azure.com/' if is_public_azure else 'https://portal.azure.us/' subscription_id = get_subscription_id(cmd.cli_ctx) tenant_id = profile.get_subscription(subscription=client.config.subscription_id)['tenantId'] settings_url = host + '#@{}/resource/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/app_settings'.format(tenant_id, subscription_id, resource_group_name, resource_name) # pylint: disable=line-too-long logger.warning('"MicrosoftAppPassword" and "botFilePath" not found in application settings') logger.warning('To see your bot\'s application settings, visit %s' % settings_url) logger.warning('To visit your deployed bot\'s code on Azure, visit Kudu for your bot at %s' % scm_url) elif not app_password and bot_file: # We have the information we need to obtain the MSA App app password via bot file data from Kudu. kudu_client = KuduClient(cmd, resource_group_name, resource_name, raw_bot_properties, logger) bot_file_data = kudu_client.get_bot_file(bot_file) app_password = BotJsonFormatter.__decrypt_bot_file(bot_file_data, bot_file_secret, logger, password_only) return { 'type': 'abs', 'id': raw_bot_properties.name, 'name': raw_bot_properties.properties.display_name, 'appId': raw_bot_properties.properties.msa_app_id, 'appPassword': app_password, 'endpoint': raw_bot_properties.properties.endpoint, 'resourceGroup': str(resource_group_name), 'tenantId': profile.get_subscription(subscription=client.config.subscription_id)['tenantId'], 'subscriptionId': client.config.subscription_id, 'serviceName': resource_name }
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, no_self_perms=None, tags=None): from azure.mgmt.keyvault.models import ( VaultCreateOrUpdateParameters, Permissions, KeyPermissions, SecretPermissions, CertificatePermissions, StoragePermissions, AccessPolicyEntry, Sku, VaultProperties) from azure.cli.core._profile import Profile from azure.graphrbac.models import GraphErrorException from azure.graphrbac import GraphRbacManagementClient 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 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) 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_bot_json( cmd, client, resource_group_name, resource_name, logger, app_password=None, # pylint:disable=too-many-locals raw_bot_properties=None, password_only=True): """ :param cmd: :param client: :param resource_group_name: :param resource_name: :param logger: :param app_password: :param raw_bot_properties: :return: Dictionary """ if not raw_bot_properties: raw_bot_properties = client.bots.get( resource_group_name=resource_group_name, resource_name=resource_name) # Initialize names bot_file and secret to capture botFilePath and botFileSecret values from the application's # settings. bot_file = None bot_file_secret = None profile = Profile(cli_ctx=cmd.cli_ctx) if not app_password: site_name = WebAppOperations.get_bot_site_name( raw_bot_properties.properties.endpoint) app_settings = WebAppOperations.get_app_settings( cmd=cmd, resource_group_name=resource_group_name, name=site_name) app_password_values = [ item['value'] for item in app_settings if item['name'] == 'MicrosoftAppPassword' ] app_password = app_password_values[ 0] if app_password_values else None if not app_password: bot_file_values = [ item['value'] for item in app_settings if item['name'] == 'botFilePath' ] bot_file = bot_file_values[0] if bot_file_values else None bot_file_secret_values = [ item['value'] for item in app_settings if item['name'] == 'botFileSecret' ] bot_file_secret = bot_file_secret_values[ 0] if bot_file_secret_values else None if not bot_file and not app_password: bot_site_name = WebAppOperations.get_bot_site_name( raw_bot_properties.properties.endpoint) scm_url = WebAppOperations.get_scm_url(cmd, resource_group_name, bot_site_name, None) # TODO: Reevaluate "Public-or-Gov" Azure logic. is_public_azure = ( 'azurewebsites.net' in raw_bot_properties.properties.endpoint or '.net' in raw_bot_properties.properties.endpoint or '.com' in raw_bot_properties.properties.endpoint) host = 'https://portal.azure.com/' if is_public_azure else 'https://portal.azure.us/' subscription_id = get_subscription_id(cmd.cli_ctx) tenant_id = profile.get_subscription( subscription=client.config.subscription_id)['tenantId'] settings_url = host + '#@{}/resource/subscriptions/{}/resourceGroups/{}/providers/Microsoft.BotService/botServices/{}/app_settings'.format(tenant_id, subscription_id, resource_group_name, resource_name) # pylint: disable=line-too-long logger.warning( '"MicrosoftAppPassword" and "botFilePath" not found in application settings' ) logger.warning( 'To see your bot\'s application settings, visit %s' % settings_url) logger.warning( 'To visit your deployed bot\'s code on Azure, visit Kudu for your bot at %s' % scm_url) elif not app_password and bot_file: # We have the information we need to obtain the MSA App app password via bot file data from Kudu. kudu_client = KuduClient(cmd, resource_group_name, resource_name, raw_bot_properties, logger) bot_file_data = kudu_client.get_bot_file(bot_file) app_password = BotJsonFormatter.__decrypt_bot_file( bot_file_data, bot_file_secret, logger, password_only) return { 'type': 'abs', 'id': raw_bot_properties.name, 'name': raw_bot_properties.properties.display_name, 'appId': raw_bot_properties.properties.msa_app_id, 'appPassword': app_password, 'endpoint': raw_bot_properties.properties.endpoint, 'resourceGroup': str(resource_group_name), 'tenantId': profile.get_subscription( subscription=client.config.subscription_id)['tenantId'], 'subscriptionId': client.config.subscription_id, 'serviceName': resource_name }
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)
def show_subscription(subscription=None, expanded_view=None): profile = Profile() if not expanded_view: return profile.get_subscription(subscription) else: return profile.get_expanded_subscription_info(subscription)