How to use the oci.config.from_file function in oci

To help you get started, we’ve selected a few oci examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oracle / oci-cli / src / oci_cli / View on Github external
def build_config(command_args):
    """Load the config object from file, and apply any overrides found in command_args."""

    # In case --endpoint is specified, the 'region' entry is removed from the REQUIRED list
    # Adding it back for subsequent calls
    if "region" not in config.REQUIRED:

        client_config = config.from_file(file_location=command_args['config_file'], profile_name=command_args['profile'])
    except exceptions.ProfileNotFound as e:
        sys.exit("ERROR: " + str(e))


    # READ config keys from env variables.
    for env in cli_constants.OCI_CONFIG_ENV_VARS:
        if env in os.environ:
            client_config[cli_constants.OCI_CONFIG_ENV_VARS[env]] = os.environ[env]

    client_config["additional_user_agent"] = 'Oracle-PythonCLI/{}'.format(__version__)

    if command_args['region']:
        client_config["region"] = command_args['region']

    if command_args['debug']:
github oracle / oci-python-sdk / examples / View on Github external
def performChangeCompartment():
    global compute_client
    global work_request_client
    global availability_domain
        # read oci config
        config = oci.config.from_file()

        # create ComputeClient() with configuration
        compute_client = ComputeClient(config)

        # create WorkRequestClient() with configuration
        work_request_client = WorkRequestClient(config)

        response = getInstanceResponse()
        availability_domain =
        source_compartment_id =
        if source_compartment_id == target_compartment_id:
            errorExit(" Source and target compartment ids are same !")

        # List instance info before move
        info(' ')
        info(' Instance info before compartment move : ')
github oracle / oci-python-sdk / examples / View on Github external
# This script accepts five arguments:
#   * The ocid of the compartment for the budget, which should be the tenancy root compartment
#   * The target type of the budget, which should be COMPARTMENT or TAG.
#   * The target for the budget.
#       For COMPARTMENT budget, this should be the target compartment OCID;
#       For TAG budget, this should be the target tag in String format 'TagNamespace.TagDefinition.TagValue'.
#   * The amount for the budget, which should an unformatted number.
#   * An email address to be used as the budget alert rule recipient.

import oci
import sys

# Default config file and profile
config = oci.config.from_file()
budget_client = oci.budget.BudgetClient(config)

if len(sys.argv) != 6:
    raise RuntimeError('This example expects 5 arguments: compartment OCID, target type (COMPARTMENT or TAG), target (compartment OCID or cost tracking tag in String format \'TagNamespace.TagDefinition.TagValue\', budget amount, alert rule recipient')

# The first argument is the name of the script, so start the index at 1
compartment_id = sys.argv[1]
target_type = sys.argv[2]
target = sys.argv[3]
amount = sys.argv[4]
recipient = sys.argv[5]

# create a budget
create_budget_response = budget_client.create_budget(
github oracle / oci-python-sdk / examples / View on Github external
        result_to_return = waiter_result
        print("Change compartment response is {}.".format(
        return result_to_return
    except Exception as e:
        raise oci.exceptions.CompositeOperationError(partial_results=[response], cause=e)

if len(sys.argv) != 3:
    raise RuntimeError(
        'This example expects an ocid for the secret to read.')

compartment_id = sys.argv[1]
oci_profile = sys.argv[2]

config = config = oci.config.from_file(

secret_content = "TestContent"
secret_name = "TestSecret"
VAULT_NAME = "KmsVault"
KEY_NAME = "KmsKey"

# Vault client to create vault
kms_vault_client = oci.key_management.KmsVaultClient(config)
kms_vault_client_composite = oci.key_management.KmsVaultClientCompositeOperations(

# This will create a vault in the given compartment
vault = create_vault(compartment_id, VAULT_NAME, kms_vault_client_composite).data
# vault = get_vault(kms_vault_client, vault_id).data
github oracle / oci-python-sdk / examples / View on Github external
database = database_client.get_database(
    print('\nGet Database')

if len(sys.argv) != 5:
    raise RuntimeError('Invalid number of arguments provided to the script. Consult the script header for required arguments')

compartment_id = sys.argv[1]
availability_domain = sys.argv[2]
cidr_block = sys.argv[3]
ssh_public_key_path = os.path.expandvars(os.path.expanduser(sys.argv[4]))

# Default config file and profile
config = oci.config.from_file()
database_client = oci.database.DatabaseClient(config)
virtual_network_client = oci.core.VirtualNetworkClient(config)

list_db_system_shapes(database_client, compartment_id)
list_db_versions(database_client, compartment_id)

vcn = None
subnet = None
    vcn = create_vcn(virtual_network_client, compartment_id, cidr_block)
    subnet = create_subnet(virtual_network_client, vcn, availability_domain)

    with open(ssh_public_key_path, mode='r') as file:
        ssh_key =

    launch_db_system_details = oci.database.models.LaunchDbSystemDetails(
github oracle / oci-python-sdk / examples / View on Github external
        except oci.exceptions.ServiceError as e:
            attempts += 1
            if e.status == 409 and attempts < 5:

config = oci.config.from_file()
iam_client = oci.identity.IdentityClient(config)
file_storage_client = oci.file_storage.FileStorageClient(config)
virtual_network_client = oci.core.VirtualNetworkClient(config)

if len(sys.argv) != 5:
    raise RuntimeError('This script expects an argument of the compartment OCID '
                       'and availability domain where the file system will be created. '
                       'It also expects defined tag namespace/key.')

# The first argument is the name of the script, so start the index at 1
compartment_id = sys.argv[1]
availability_domain = sys.argv[2]
namespace = sys.argv[3]
defined_key = sys.argv[4]

# Here we apply a retry strategy to the call to ride out any throttles, timeouts or intermittent 500s (internal server
github oracle / oci-python-sdk / examples / list_resources_in_tenancy / View on Github external
signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner(delegation_token=delegation_token)

                return config, signer

        except KeyError:
            print("* Key Error obtaining delegation_token_file")
            raise SystemExit

        except Exception:

    # -----------------------------
    # config file authentication
    # -----------------------------
        config = oci.config.from_file(
            (config_profile if config_profile else oci.config.DEFAULT_PROFILE)
        signer = oci.signer.Signer(
            pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"),
        return config, signer
github oracle / oci-python-sdk / examples / View on Github external

if len(sys.argv) != 4:
    raise RuntimeError('This script needs to be provided a compartment ID, an availability domain and a KMS key ID')

compartment_id = sys.argv[1]
availability_domain = sys.argv[2]
kms_key_id = sys.argv[3]

config = oci.config.from_file()
compute_client = oci.core.ComputeClient(config)
virtual_network_client = oci.core.VirtualNetworkClient(config)
block_storage_client = oci.core.BlockstorageClient(config)

vcn_and_subnet = None
volume = None
instance = None
    vcn_and_subnet = create_vcn_and_subnet(virtual_network_client, compartment_id, availability_domain)
    volume = create_volume(block_storage_client, compartment_id, availability_domain, 'vol_attach_example_vol', kms_key_id)
    instance = launch_instance(compute_client, vcn_and_subnet, kms_key_id)


    paravirtualized_volume_attachment_response = compute_client.attach_volume(
github oracle / oci-python-sdk / examples / View on Github external
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates.  All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at or Apache License 2.0 as shown at You may choose either license.

import oci
from oci.identity.models import AddUserToGroupDetails, CreateGroupDetails, CreateUserDetails

# Default config file and profile
config = oci.config.from_file()
compartment_id = config["tenancy"]
# Service client
identity = oci.identity.IdentityClient(config)

# Get and set the home region for the compartment. User crud operations need
# to be performed in the home region.
response = identity.list_region_subscriptions(compartment_id)
for region in
    if region.is_home_region:

user_name = "python-sdk-example-user"
group_name = "python-sdk-example-group"

print("Creating a new user {!r} in compartment {!r}".format(
github oracle / oci-python-sdk / examples / View on Github external

import oci
from datetime import datetime

# Helper to format dates
def format_time(timestamp):
    # Will be ticks, not seconds from epoch
    return datetime.utcfromtimestamp(timestamp / 1000).strftime('%Y-%m-%d %H:%M:%S')

# Default config file and profile
config = oci.config.from_file()
healthchecks_client = oci.healthchecks.HealthChecksClient(config)

# This is the root compartment.  You can use another compartment in your tenancy.
compartment_id = config["tenancy"]

# List of available vantage points
vantage_points = healthchecks_client.list_health_checks_vantage_points().data

# HttpMonitors examples
# Creating a new HttpMonitor:
http_monitor = healthchecks_client.create_http_monitor(
        display_name="Monitor Name",