Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
Setup, invoke, or, teardown a function.
:param args: The commandline args: setup, invoke, teardown
:type argv: [str]
"""
# All resources will be prefixed with this name.
name = NAME_PREFIX
# Load OCI credentials from default location and profile.
cfg = config.from_file(
file_location=os.getenv(
"OCI_CONFIG_PATH", config.DEFAULT_LOCATION),
profile_name=os.getenv(
"OCI_CONFIG_PROFILE", config.DEFAULT_PROFILE)
)
config.validate_config(cfg)
# All resources will be created in the specified compartment.
compartment_name = os.environ.get('COMPARTMENT_NAME')
if compartment_name is not None:
compartment_id = get_compartment_id(cfg, compartment_name).id
else:
compartment_id = os.environ.get('COMPARTMENT_ID')
if compartment_id is None:
print("The COMPARTMENT_ID (or COMPARTMENT_NAME) environment variable must be set.")
sys.exit(1)
# We need an accessible image to invoke.
# e.g. phx.ocir.io/tenancy-name/registry/imagename:version
image = os.environ.get('OCIR_FN_IMAGE')
if args.config is not None and path.exists(args.config):
OCIConfigFile = args.config
userName = args.username
if userName is None:
print("Username is mandatory, provide the username as -u username")
exit(-1)
groupName = args.groupname
fileName = args.certpath
if fileName is None or not path.exists(fileName):
print("Public Certificate file not provided or does not exist, provide the filepath as -f filepath")
exit(-1)
if debug:
print(userName, " : " + groupName + " : " + fileName)
# Set up config
config = oci.config.from_file(OCIConfigFile, "DEFAULT")
# Create a service client
identity = oci.identity.IdentityClient(config)
compartment_id = config["tenancy"]
search_client = oci.resource_search.ResourceSearchClient(config)
group_id = ""
main()
# The following environment variables are expected to be set for this to work.
#
# OCI_RESOURCE_PRINCIPAL_VERSION="2.2"
# OCI_RESOURCE_PRINCIPAL_RPST
# OCI_RESOURCE_PRINCIPAL_PRIVATE_PEM
# OCI_RESOURCE_PRINCIPAL_PRIVATE_PEM_PASSPHRASE
# OCI_RESOURCE_PRINCIPAL_REGION
#
# OCI_RESOURCE_PRINCIPAL_VERSION="1.1"
# OCI_RESOURCE_PRINCIPAL_RPT_ENDPOINT
# OCI_RESOURCE_PRINCIPAL_RPST_ENDPOINT
signer = oci.auth.signers.resource_principals_signer.get_resource_principals_signer()
kwargs['signer'] = signer
try:
config.validate_config(client_config, **kwargs)
except exceptions.InvalidConfig as bad_config:
table = render_config_errors(bad_config)
template = "ERROR: The config file at {config_file} is invalid:\n\n{errors}"
sys.exit(template.format(
config_file=ctx.obj['config_file'],
errors=table
))
return ConfigAndSigner(config=client_config, signer=signer, uses_instance_principals_auth=instance_principal_auth)
# * The third is the name (not OCID) of the tag namespace to use in defined tags
# * The fourth is the name of a tag in the tag namespace to use defined tags
import oci
import sys
if len(sys.argv) != 5:
raise RuntimeError('Unexpected number of arguments received. Consult the script header comments for expected arguments')
compartment_id = sys.argv[1]
bucket_name = sys.argv[2]
tag_namespace = sys.argv[3]
tag_name = sys.argv[4]
# Default config file and profile
config = oci.config.from_file()
object_storage_client = oci.object_storage.ObjectStorageClient(config)
namespace = object_storage_client.get_namespace().data
# We can assign tags to a bucket at creation time. Like other taggable resources, we can
# assign freeform and defined tags to a bucket. Freeform tags are a dictionary of
# string-to-string, where the key is the tag name and the value is the tag value.
#
# Defined tags are a dictionary where the key is the tag namespace (string) and the value is another dictionary. In
# this second dictionary, the key is the tag name (string) and the value is the tag value. The tag names have to
# correspond to the name of a tag within the specified namespace (and the namespace must exist).
create_bucket_response = object_storage_client.create_bucket(
namespace,
oci.object_storage.models.CreateBucketDetails(
name=bucket_name,
compartment_id=compartment_id,
# OCI KMS has APIs that allow creating master keys or importing a previously generated key, either will work.
# You can refer to the example at examples/kms_example.py for an example of how to create a master key.
# Update the values for VAULT_ID and MASTER_KEY_ID below with the values for your vault and key and then run
# the example.
import shutil
import filecmp
import oci
# TODO: populate variables below
VAULT_ID = ""
MASTER_KEY_ID = ""
# load default configuration from ~/.oci/config
config = oci.config.from_file()
# if you want to target a region other than the one specified
# in your config, you must override 'region' in the config
# before initializing the MasterKey and MasterKeyProvider
config['region'] = 'us-phoenix-1'
kms_master_key = oci.encryption.KMSMasterKey(
config=config, master_key_id=MASTER_KEY_ID, vault_id=VAULT_ID
)
kms_master_key_provider = oci.encryption.KMSMasterKeyProvider(
config=config,
kms_master_keys=[kms_master_key]
)
###############################################
succeed_on_not_found=True
)
# ---------- assign provided arguments
compartment_id = args.compartment_id
vcn_id = args.vcn_id
availability_domain = args.availability_domain
display_name = args.display_name
# vnic_id = args.vnic_id
subnet_id = args.subnet_id
image_id = args.image_id
# ---------- read config from file
config = oci.config.from_file()
compute_client = oci.core.ComputeClient(config)
virtual_network_client = oci.core.VirtualNetworkClient(config)
# Create Network Security Group objects
print("==================")
print("Creating network security group")
print("==================")
new_nsg = create_nsg(virtual_network_client, vcn_id, display_name)
nsg_id = new_nsg.id
print("==================")
print("Created network security group {}".format(nsg_id))
print("==================")
time.sleep(2)
print("==================")
print("Creating second network security group")
print("==================")
compartment_id=compartment_id,
vcn_id=vcn_id,
display_name=display_name,
services=list()
)
response_data = virtual_network_client.create_service_gateway_and_wait_for_state(
create_sgw_details,
wait_for_states=[oci.core.models.ServiceGateway.LIFECYCLE_STATE_AVAILABLE]
).data
print("Created Service Gateway %s" % response_data.id)
# ---------- read config from file
config = oci.config.from_file()
compute_client = oci.core.ComputeClient(config)
# Create Virtual Network Client with configuration for composite operations
virtual_network_client = oci.core.VirtualNetworkClientCompositeOperations(
oci.core.VirtualNetworkClient(config)
)
# create Service Gateway
create_service_gateway(
virtual_network_client,
compartment_id,
vcn_id,
display_name
)
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
# This script provides an example of how use database CLI in terms of:
# - Retrieving a DbHome within a given VmCluster
# Usage: python exacc_dbhome_get_example.py
import oci
import sys
if len(sys.argv) < 2:
print("Missing argument! an OCID for a DbHome!")
db_home_id = sys.argv[1]
config = oci.config.from_file()
client = oci.database.DatabaseClient(config)
response = client.get_db_home(db_home_id=db_home_id)
print(response.data)
database = oci.database.DatabaseClient(config={}, signer=signer)
pool = oci.core.ComputeManagementClient(config={}, signer=signer)
search = oci.resource_search.ResourceSearchClient(config={}, signer=signer)
ns = oci.ons.NotificationDataPlaneClient(config={}, signer=signer)
while SearchRootID:
compartment = identity.get_compartment(compartment_id=SearchCompID).data
if compartment.compartment_id[:14] == "ocid1.tenancy.":
RootCompartmentID = compartment.compartment_id
SearchRootID = False
else:
SearchCompID = compartment.compartment_id
else:
config = oci.config.from_file(configfile)
identity = oci.identity.IdentityClient(config)
compute = oci.core.ComputeClient(config)
database = oci.database.DatabaseClient(config)
pool = oci.core.ComputeManagementClient(config)
search = oci.resource_search.ResourceSearchClient(config)
ns = oci.ons.NotificationDataPlaneClient(config)
user = identity.get_user(config["user"]).data
userName = user.description
RootCompartmentID = config["tenancy"]
region = config["region"]
# Check credentials and enabled regions
Tenancy = identity.get_tenancy(tenancy_id=RootCompartmentID).data
MakeLog ("Logged in as: {}/{} @ {}".format(userName, Tenancy.name, region))
return config, signer
except KeyError:
print("* Key Error obtaining delegation_token_file")
raise SystemExit
except Exception:
raise
# -----------------------------
# config file authentication
# -----------------------------
else:
config = oci.config.from_file(
oci.config.DEFAULT_LOCATION,
(config_profile if config_profile else oci.config.DEFAULT_PROFILE)
)
signer = oci.signer.Signer(
tenancy=config["tenancy"],
user=config["user"],
fingerprint=config["fingerprint"],
private_key_file_location=config.get("key_file"),
pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"),
private_key_content=config.get("key_content")
)
return config, signer