def __init__(self, json_config=None): if json_config: self.config = from_file(profile_name=json_config.get("profile")) else: self.config = from_file() self._identity_client = IdentityClient(self.config) self._compute_client = ComputeClient(self.config) self._network_client = VirtualNetworkClient(self.config)
def count_instances(filters: List[Dict[str, Any]], compartment_id: str = None, configuration: Configuration = None, secrets: Secrets = None) -> int: """ Return the number of instances in accordance with the given filters. Please refer to: https://oracle-cloud-infrastructure-python-sdk.readthedocs.io/en/latest/api/core/models/oci.core.models.Instance.html#oci.core.models.Instance for details on the available filters under the 'parameters' section. """ # noqa: E501 compartment_id = compartment_id or from_file().get('compartment') if compartment_id is None: raise ActivityFailed('We have not been able to find a compartment,' ' without one, we cannot continue.') client = oci_client(ComputeClient, configuration, secrets, skip_deserialization=False) filters = filters or None instances = get_instances(client, compartment_id) if filters is not None: return len(filter_instances(instances, filters=filters)) return len(instances)
def loadConfig(ProfileName): click.echo('Using the Profile: %s' % ProfileName) try: config = from_file(profile_name=ProfileName) except: click.echo('Not Found for the Profile: %s, Please check the profile in config file.' % ProfileName) sys.exit(0) return config
def _get_oci_config(self): oci_config_file = path.join(path.expanduser("~"), ".oci", "config") oci_config_profile = 'DEFAULT' if "OCI_CONFIG_PROFILE" in environ: oci_config_profile = environ.get("OCI_CONFIG_PROFILE") elif self.get_option("oci_profile") is not None: oci_config_profile = self.get_option('oci_profile') return config.from_file(file_location=oci_config_file, profile_name=oci_config_profile)
def pa_finalize(ctx, from_json, appliance_profile, job_id, appliance_label, skip_upload_user_check): click.echo("Retrieving the upload summary object name from Oracle Cloud Infrastructure") appliance_client = cli_util.build_client('dts', 'transfer_appliance', ctx) physical_appliance_client = create_appliance_client(ctx, appliance_profile) upload_summary_obj_name = appliance_client.get_transfer_appliance( id=job_id, transfer_appliance_label=appliance_label ).data.upload_status_log_uri click.echo("Retrieving the upload bucket name from Oracle Cloud Infrastructure") client = cli_util.build_client('dts', 'transfer_job', ctx) upload_bucket = client.get_transfer_job(id=job_id).data.upload_bucket_name if not skip_upload_user_check: click.echo("Validating the upload user credentials") validate_upload_user_credentials(ctx, upload_bucket) click.echo("Storing the upload user configuration and credentials on the transfer appliance") upload_user_config = oci_config.from_file(APPLIANCE_UPLOAD_USER_CONFIG_PATH) upload_user_key_file = open(os.path.expanduser(upload_user_config[KEY_FILE_KEY])).read() upload_config = { 'uploadBucket': upload_bucket, 'overwrite': False, 'objectNamePrefix': "", 'uploadSummaryObjectName': upload_summary_obj_name, 'uploadUserOciConfig': open(APPLIANCE_UPLOAD_USER_CONFIG_PATH).read(), 'uploadUserPrivateKeyPem': upload_user_key_file } physical_appliance_client.set_object_storage_upload_config(upload_config=upload_config) click.echo("Finalizing the transfer appliance...") physical_appliance_client.finalize_appliance() appliance_info = physical_appliance_client.get_physical_transfer_appliance() click.echo("The transfer appliance is locked after finalize. Hence the finalize status will be shown as NA. " "Please unlock the transfer appliance again to see the correct finalize status") click.echo("Changing the state of the transfer appliance to FINALIZED") current_state = appliance_client.get_transfer_appliance( id=job_id, transfer_appliance_label=appliance_label ).data.lifecycle_state if current_state != TransferAppliance.LIFECYCLE_STATE_FINALIZED: details = { "lifecycleState": TransferAppliance.LIFECYCLE_STATE_FINALIZED } appliance_client.update_transfer_appliance( id=job_id, transfer_appliance_label=appliance_label, update_transfer_appliance_details=details) user_friendly_appliance_info = convert_to_user_friendly(appliance_info) cli_util.render_response(user_friendly_appliance_info, ctx)
def _get_oci_dns_client(): oci_config_file = path.join(path.expanduser("~"), ".oci", "config") oci_config_profile = 'DEFAULT' if "OCI_CONFIG_PROFILE" in environ: oci_config_profile = environ.get("OCI_CONFIG_PROFILE") oci_config = config.from_file(file_location=oci_config_file, profile_name=oci_config_profile) return DnsClient(oci_config)
def get_upload_user_config(): try: upload_user_config = oci_config.from_file( file_location=APPLIANCE_UPLOAD_USER_CONFIG_PATH, profile_name="DEFAULT") return upload_user_config except exceptions.ConfigFileNotFound as e: error_message_wrapper( 'Unable to parse the upload user config file %s: %s' % (APPLIANCE_UPLOAD_USER_CONFIG_PATH, e))
def get_configuration(): """ get the config file typically expected in ~/.oci/config """ global configuration if configuration is None: configuration = from_file() # print("configuration: {}".format(configuration)) return configuration
def __init__(self, config_file, config_section, logger=None): ''' Create ObjectStorageClient for OCI config_file : OCI Configuration File config_section : OCI Config File Section logger : Logger, if not given one will be created ''' config = from_file(config_file, config_section) self.object_storage_client = ObjectStorageClient(config, retry_strategy=DEFAULT_RETRY_STRATEGY) self.upload_manager = UploadManager(self.object_storage_client) if logger is None: self.logger = setup_logger("oci_client", 10) else: self.logger = logger
def authenticate(self, profile=None, **kwargs): try: config = from_file(profile_name=profile) compartment_id = config["tenancy"] # Get the current user identity = IdentityClient(config) identity.get_user(config["user"]).data return OracleCredentials(config, compartment_id) except Exception as e: raise AuthenticationException(e)
def oci_client(resource_name: str, configuration: Configuration = None, secrets: Secrets = None, skip_deserialization: bool = False): """Create an oci configuration object""" # As secrets is attached to configuration in OCI, it is not used. configuration = configuration or {} if not configuration.get('tenancy'): configuration = from_file() else: validate_config(configuration) return resource_name(configuration, skip_deserialization=skip_deserialization)
def main(ctx, config_file, profile): user_config = config.from_file(file_location=config_file, profile_name=profile) global Default_CompartmentID,Default_Region if "compartment_id" in user_config: Default_CompartmentID = user_config["compartment_id"] else: click.echo('>>> Error: No compartment_id found at : %s, with Profile: %s' % (config_file, profile)) click.echo('>>> Error: Before use any sub-command, your need to update your config file with compartment_id.') exit(0) Default_Region = user_config["region"] #print(Default_CompartmentID) #print(Default_Region) ctx.obj = user_config click.echo(click.style('▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄[ Backup Management Started ]▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄', fg='yellow', bg='black',bold=True)) click.echo('█\n█ → Using the Configuration file: %s, and Profile: %s' % (config_file, profile)) click.echo('█'+click.style('-------------------------------------------------', fg='yellow'))
def authenticate(self, profile=None, **kwargs): try: # Set logging level to error for libraries as otherwise generates a lot of warnings logging.getLogger('oci').setLevel(logging.ERROR) config = from_file(profile_name=profile) # Get the current user identity = IdentityClient(config) identity.get_user(config["user"]).data return OracleCredentials(config) except Exception as e: raise AuthenticationException(e)
def _setup_credentials(self): if self.conf('credentials') is None: oci_config_file = path.join(path.expanduser("~"), ".oci", "config") elif self.conf('credentials') == 'instance_principal': self.credentials = InstancePrincipalsSecurityTokenSigner() return else: oci_config_file = self.conf('credentials') oci_config_profile = 'DEFAULT' if self.conf('profile') is not None: oci_config_profile = self.conf('profile') elif 'OCI_CONFIG_PROFILE' in environ: oci_config_profile = environ.get('OCI_CONFIG_PROFILE') self.credentials = config.from_file(file_location=oci_config_file, profile_name=oci_config_profile)
def _get_valid_oci_config(self, oci_path=None, profile_name="DEFAULT"): """Get a valid OCI config from the given configuration file path""" try: from oci import config, exceptions except ImportError: raise errors.ProgrammingError( 'Package "oci" (Oracle Cloud Infrastructure Python SDK)' ' is not installed.') if not oci_path: oci_path = config.DEFAULT_LOCATION error_list = [] req_keys = { "fingerprint": (lambda x: len(x) > 32), "key_file": (lambda x: os.path.exists(os.path.expanduser(x))) } try: # key_file is validated by oci.config if present oci_config = config.from_file(oci_path, profile_name) for req_key in req_keys: try: # Verify parameter in req_key is present and valid if oci_config[req_key] \ and not req_keys[req_key](oci_config[req_key]): error_list.append(f'Parameter "{req_key}" is invalid') except KeyError as err: error_list.append(f'Does not contain parameter {req_key}') except (exceptions.ConfigFileNotFound, exceptions.InvalidConfig, exceptions.InvalidKeyFilePath, exceptions.InvalidPrivateKey, exceptions.MissingPrivateKeyPassphrase, exceptions.ProfileNotFound) as err: error_list.append(str(err)) # Raise errors if any if error_list: raise errors.ProgrammingError( f'Invalid profile {profile_name} in: "{oci_path}". ' f" Errors found: {error_list}") return oci_config
def stop_random_instance(filters: List[Dict[str, Any]], compartment_id: str = None, force: bool = False, configuration: Configuration = None, secrets: Secrets = None) -> OCIResponse: """ Stop a a random compute instance within a given compartment. If filters are provided, the scope will be reduced to those instances matching the filters. Please refer to: https://oracle-cloud-infrastructure-python-sdk.readthedocs.io/en/latest/api/core/models/oci.core.models.Instance.html#oci.core.models.Instance for details on the available filters under the 'parameters' section. """ # noqa: E501 client = oci_client(ComputeClient, configuration, secrets, skip_deserialization=False) action = "STOP" if force else "SOFTSTOP" compartment_id = compartment_id or from_file().get('compartment') if compartment_id is None: raise ActivityFailed('We have not been able to find a compartment,' ' without one, we cannot continue.') instances = get_instances(client, compartment_id) filters = filters or None if filters is not None: instances = filter_instances(instances, filters=filters) instance_id = choice(instances).id s_client = oci_client(ComputeClient, configuration, secrets, skip_deserialization=True) ret = s_client.instance_action(instance_id=instance_id, action=action) return ret.data
def _get_oci_config(): """ To unify different tools (oci-cli, ortu, ansible, terraform), I'm using the following doc https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/clienvironmentvariables.htm#CLI_Environment_Variables :return: oci_config """ oci_user = environ.get("OCI_CLI_USER") oci_fingerprint = environ.get("OCI_CLI_FINGERPRINT") oci_tenancy = environ.get("OCI_CLI_TENANCY") oci_region = environ.get("OCI_CLI_REGION") oci_key_file = environ.get("OCI_CLI_KEY_FILE") oci_key_content = environ.get("OCI_CLI_KEY_CONTENT") if oci_user and oci_fingerprint and oci_tenancy and oci_region and ( oci_key_file or oci_key_content): oci_config = { "user": oci_user, "fingerprint": oci_fingerprint, "tenancy": oci_tenancy, "region": oci_region } if oci_key_file: oci_config["key_file"] = oci_key_file elif oci_key_content: oci_config["key_content"] = oci_key_content else: oci_config_file = environ.get( "OCI_CLI_CONFIG_FILE", path.join(path.expanduser("~"), ".oci", "config")) oci_config_profile = environ.get( "OCI_CONFIG_PROFILE", environ.get("OCI_CLI_PROFILE", "DEFAULT")) oci_config = config.from_file(file_location=oci_config_file, profile_name=oci_config_profile) config.validate_config(oci_config) return oci_config
import oci from oci.config import from_file import atp, regions import sys """ Example scripts demonstrating how to use the ATP Rest APIs for python Usage: python deleteAutonomousDatabase.py start Delete the database given the DB OCID """ #Setup config = from_file(file_location="/root/.oci/config") try: if len(sys.argv) == 2: exampleDelete = atp.deleteAutonomousDatabase(config, sys.argv[1]) print("Response: " + str(exampleDelete)) else: print("Please add the Database OCID as the argument!") except Exception as e: print(e)
'.oci/oci_api_key_public.pem') if not os.path.exists('.oci/config'): logging.error("File .oci/config missing!") exit(1) if not os.path.exists('.oci/oci_api_key.pem'): logging.error("File .oci/oci_api_key.pem missing!") exit(1) if not os.path.exists('.oci/oci_api_key_public.pem'): logging.error("File .oci/oci_api_key_public.pem missing!") exit(1) logging.info("Loading configuration from .oci") config = from_file(file_location=".oci/config") logging.info("Validating configuration from .oci") validate_config(config) identity = IdentityClient(config) tenant_compartment_id = config["tenancy"] logging.info("Retrieving all compartments") compartments = getCompartmentRecurse(identity, tenant_compartment_id) logging.debug(compartments) if compartments.get(newCompartmentName) is not None: logging.error("Compartment already exists!") sendMail(newCompartmentOwner, "Subscription already exists", "Subscription %s already exists!" % newCompartmentName) exit(2)
import oci from oci.config import from_file import atp, regions import sys """ Example scripts demonstrating how to use the ATP Rest APIs for python Usage: python createAutonomousDatabase.py DatabaseName DisplayName Password CPUCount StorageSizeInTBs Creates an Autonomous Database Instance with given parameters """ #Setup config = from_file(file_location="./oci-config") try: #print(config #Database body to create body = { "compartmentId": config["compartmentid"], "displayName": sys.argv[1], "dbName": sys.argv[2], "adminPassword": sys.argv[3], "cpuCoreCount": int(sys.argv[4]), "dataStorageSizeInTBs": int(sys.argv[5]) } exampleCreate = atp.createAutonomousDatabase(config, body)
import oci from oci.config import from_file import base64 import DataKeyManagement config = from_file(file_location="C:\\Users\\...config", profile_name='DEFAULT') # Manages encryption of actual data. def encryptdata(masterkeyocid, artifact, plain_text): # This function is called when actual Data needs to be encrypted. # Note:- Artifact is the Encrypted Data Key passed to the function just for this example. # The Artifact should stored securely and only this code should have access to it. masterkey = masterkeyocid key_management_client = oci.key_management.KmsCryptoClient( config, "https://your_crypto_head.oraclecloud.com") encrypt_data_details = oci.key_management.models.EncryptDataDetails( key_id=DataKeyManagement.decryptdatakey(masterkey, artifact), plaintext=plain_text) encrypt_response = key_management_client.encrypt(encrypt_data_details) return encrypt_response def decryptdata(masterkey, artifact, cipher_text): # This function is called when actual Data needs to be decrypted. # The Data Key OCID is passed inline calling methods from DataKeyManagement.py file. key_management_client = oci.key_management.KmsCryptoClient( config, "https://your_crypto_head.oraclecloud.com") decrypt_data_details = oci.key_management.models.DecryptDataDetails( key_id=DataKeyManagement.decryptdatakey(masterkey, artifact),
# - Update the previously created Quota # - Delete this Quota # Description of Parameters # compartment_id : The OCID of the compartment where Quotas will reside (this has to be the root compartment) # name : Name of the Quota # description : Description for the Quota # statements : An array of Quota statements written in the declarative language # Required imports from oci import config from oci.limits import QuotasClient from oci.limits.models import CreateQuotaDetails, UpdateQuotaDetails # User configs user_config = config.from_file() # Sample inputs compartment_id = user_config["tenancy"] name = "MyQuota" description = "This is a sample Quota" statements = ["Zero test-family quota 'test-quota-1' in tenancy"] # Client initialization quotas_client = QuotasClient(user_config) # Create print("Creating a Quota") create_quota_details = CreateQuotaDetails(compartment_id=compartment_id, name=name, description=description, statements=statements) response = quotas_client.create_quota(create_quota_details) created_quota = response.data
db_wallet_secret_name = "wallet" + "this-is-not-the-secret" + "dbname" # Display OCI Python SDK version print("oci version:", pkg_resources.get_distribution("oci").version) # Set do_clean_up_at_end to false to keep the Database Tools Private Endpoint, secrets and connection created do_clean_up_at_end = True # Variables wallet_secret_id = None password_secret_id = None private_endpoint_id = None connection_id = None # Load OCI Config oci_config = from_file(file_location="~/.oci/config", profile_name="DEFAULT") # Validate OCI Config validate_config(oci_config) # Prepare all clients that we will need db_client, db_async_client = get_database_clients(oci_config) vaults_client, vaults_async_client = get_vaults_clients(oci_config) kms_vault_client = get_kms_vault_client(oci_config) secrets_client = get_secrets_client(oci_config) dbtools_client, dbtools_async_client = get_dbtools_clients(oci_config) # Prepare a dict that contains all the required clients clients = { "db_client": db_client, "db_async_client": db_async_client,
# coding: utf-8 # Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. import requests from oci.config import from_file from oci.signer import Signer config = from_file() auth = Signer( tenancy=config['tenancy'], user=config['user'], fingerprint=config['fingerprint'], private_key_file_location=config['key_file'], pass_phrase=config['pass_phrase'] ) endpoint = 'https://identity.us-phoenix-1.oraclecloud.com/20160918/users/' body = { 'compartmentId': config['tenancy'], # root compartment 'name': 'TestUser', 'description': 'Created with a raw request' } response = requests.post(endpoint, json=body, auth=auth) response.raise_for_status() print(response.json()['id'])
def validate_upload_user_credentials(ctx, upload_bucket): """ There are two users, the admin user and the upload user The admin user is the one who has access to the user's tenancy and can perform operations like creating a job, requesting an appliance, etc. The upload user has enough permissions to just upload data to a particular user bucket. The upload user cannot delete objects from the bucket nor can it make modifications to the bucket or account. In essence it is a restricted user. The upload user is defined in ~/.oci/config_upload_user under the [DEFAULT] section. There is no way to change the file and the section. These are standards that are expected The idea of validation is to check whether the upload user has the ability to create objects, inspect the object and read the object's meta data from Oracle Cloud Infrastructure The procedure is this: 1. Admin user tries to get the test object and delete it if it is present. - This is more of an error check when there is a stale object present from a previous failed run - Only the admin user, NOT the upload user, can delete an object 2. Upload user creates the test object 3. Upload user overwrites the test object 4. Upload user gets the checksum of the test object 5. Upload user gets the metadata of the test bucket 6. Admin user deletes the test object :param upload_bucket: The bucket to upload to :return: None """ admin_user = oci_config.from_file(ctx.obj['config_file'])['user'] # Overriding any endpoint that was set. Need to get to the endpoint based on the config file, not based on the # override parameter ctx.endpoint = None ctx.obj['endpoint'] = None object_storage_admin_client = cli_util.build_client('object_storage', ctx) # A bit hacky but gets the job done. Only two parameters need to be changed to get the upload user context, # the profile and the config file. All other parameters remain the same upload_user_ctx = ctx upload_user_ctx.obj['profile'] = 'DEFAULT' upload_user_ctx.obj['config_file'] = APPLIANCE_UPLOAD_USER_CONFIG_PATH # Overriding any endpoint that was set. Need to get to the endpoint based on the config_upload_user file upload_user_ctx.endpoint = None object_storage_upload_client = cli_util.build_client( 'object_storage', upload_user_ctx) namespace = object_storage_admin_client.get_namespace().data try: try: object_storage_admin_client.head_object(namespace, upload_bucket, TEST_OBJECT) click.echo("Found test object in bucket. Deleting it...") object_storage_admin_client.delete_object(namespace, upload_bucket, TEST_OBJECT) except exceptions.ServiceError as se: if se.status != 404: raise se except Exception as e: raise exceptions.RequestException( "Admin user {} failed to delete the test object {}: {}".format( admin_user, TEST_OBJECT, str(e))) test_object_content = "Bulk Data Transfer Test" operation = None test_object_exists = False try: operation = "Create object {} in bucket {} using upload user".format( TEST_OBJECT, upload_bucket) object_storage_upload_client.put_object(namespace, upload_bucket, TEST_OBJECT, test_object_content) click.echo(operation) test_object_exists = True operation = "Overwrite object {} in bucket {} using upload user".format( TEST_OBJECT, upload_bucket) object_storage_upload_client.put_object(namespace, upload_bucket, TEST_OBJECT, test_object_content) click.echo(operation) operation = "Inspect object {} in bucket {} using upload user".format( TEST_OBJECT, upload_bucket) object_storage_upload_client.head_object(namespace, upload_bucket, TEST_OBJECT) click.echo(operation) operation = "Read bucket metadata {} using upload user".format( upload_bucket) metadata = object_storage_upload_client.get_bucket( namespace, upload_bucket).data.metadata click.echo(operation) except exceptions.ServiceError as se: raise exceptions.RequestException( "Failed to {} in tenancy {} as upload user: {}".format( operation, namespace, se.message)) finally: if test_object_exists: try: object_storage_admin_client.delete_object( namespace, upload_bucket, TEST_OBJECT) except exceptions.ServiceError as se: raise exceptions.ServiceError( "Failed to delete test object {} as admin user {}: {}". format(TEST_OBJECT, admin_user, se.message))
# coding: utf-8 # Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. import requests from oci.config import from_file from oci.signer import Signer config = from_file() auth = Signer(tenancy=config['tenancy'], user=config['user'], fingerprint=config['fingerprint'], private_key_file_location=config['key_file'], pass_phrase=config['pass_phrase']) endpoint = 'https://identity.us-phoenix-1.oraclecloud.com/20160918/users/' body = { 'compartmentId': config['tenancy'], # root compartment 'name': 'TestUser', 'description': 'Created with a raw request' } response = requests.post(endpoint, json=body, auth=auth) response.raise_for_status() print(response.json()['id'])
# For this we use OCI SDK and Flask/waitress server. # We also use a JSON file which is a configuration file # In the configuration file, we provide IP addresses of the 2 VM which are sending simple HTTP request. PaloAlto Networks VM are able to send an HTTP request in case they need to do move from active to standby VM. # The Python script analyzes IP source address of the request. Based on the IP source, it will move from VM1 to VM2 or the other side. # You can test your JSON file and be sure atht you are using the right IP addresses with the python scripts: # test_json_ip_address_SDK.py import json import oci import email.utils from oci.config import from_file config = from_file(profile_name="essilor") # need to run flask in virtual environnement pip install flask from flask import Flask, request from waitress import serve # needed for waitress app = Flask(__name__) app.debug = True # need this for autoreload as and stack trace with open('oci_value_IP_address.json') as json_file: Entries = json.load(json_file) # virtual_network = oci.core.VirtualNetworkClient(config) def getPrivateIP (IP,MysubnetID): """This function will get the VNICID and ID of the privateIP based on its IP address\ and subnetIP. Error=0 if the request was ok. If not, result is 1) """
def get_user(ctx): return oci_config.from_file(ctx.obj['config_file'])['user']
# Version 0.9 # Author: [email protected] # Test of JSON file with API clal on OCI # API reference # https://docs.cloud.oracle.com/iaas/api/#/en/iaas/20160918/PrivateIp/ # pip install httpsig_cffi requests six # import httpsig_cffi.sign import json import oci from oci.config import from_file config = from_file(profile_name="yourprofile") # need to run flask in virtual environnement pip install flask from flask import Flask, request app = Flask(__name__) app.debug = True # need this for autoreload as and stack trace with open('oci_value_IP_address.json') as json_file: Entries = json.load(json_file) virtual_network = oci.core.VirtualNetworkClient(config) def getPrivateIP (IP,MysubnetID): print("\nRequesting:"+IP) getIP=virtual_network.list_private_ips(ip_address=IP, subnet_id=MysubnetID) JSON_ANSWER_raw=getIP.data error=0 # Warning in private_ip.data there are som extra \n you need to remove
raise Exception("function not found") if __name__ == "__main__": if len(sys.argv) != 5: raise Exception("usage: python invoke_function.py" " <compartment-name> <app-name> " "<function-name> <request payload>") compartment_name = sys.argv[1] app_name = sys.argv[2] fn_name = sys.argv[3] cfg = config.from_file(file_location=os.getenv("OCI_CONFIG_PATH", config.DEFAULT_LOCATION), profile_name=os.getenv("OCI_CONFIG_PROFILE", config.DEFAULT_PROFILE)) if int(os.getenv("DEBUG", "0")) > 0: requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True cfg.update({"log_requests": True}) functions_client = functions.FunctionsManagementClient(cfg) config.validate_config(cfg) compartment = get_compartment(cfg, compartment_name) app = get_app(functions_client, app_name, compartment) fn = get_function(functions_client, app, fn_name)
def get_user(ctx): if 'user' in ctx.obj['config']: return ctx.obj['config']['user'] return oci_config.from_file(ctx.obj['config_file'])['user']