def __init__(self, config, subnet): self.config = config self.client = ComputeClient(config) self.operating_systems = self.get_operating_systems() self.subnet = subnet self.keyfile = 'private'+self.subnet.availability_domain[-1]+'.pem' self.name = self.config['display_name']+' '+self.subnet.availability_domain[-1]
def main(): module_args = oci_utils.get_common_arg_spec() module_args.update( dict(compartment_id=dict(type='str', required=False), image_id=dict(type='str', required=False, aliases=['id']))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=False, mutually_exclusive=['id', 'compartment_id']) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) compartment_id = module.params['compartment_id'] id = module.params['image_id'] result = dict(changed=False) try: if compartment_id: inst = oci_utils.list_all_resources(compute_client.list_images, compartment_id=compartment_id) result = to_dict(inst) else: inst = oci_utils.call_with_backoff(compute_client.get_image, image_id=id).data result = to_dict([inst]) except ServiceError as ex: module.fail_json(msg=ex.message) except MaximumWaitTimeExceeded as mwte: module.fail_json(msg=str(mwte)) module.exit_json(images=result)
def set_connect(self, secret_data): self.identity_client = IdentityClient(secret_data) self.database_client = DatabaseClient(secret_data) self.disk_client = BlockstorageClient(secret_data) self.compute_client = ComputeClient(secret_data) self.compute_management_client = ComputeManagementClient(secret_data) self.virtual_network_client = VirtualNetworkClient(secret_data) self.load_balancer_client = LoadBalancerClient(secret_data) self.network_load_balancer_client = NetworkLoadBalancerClient(secret_data)
def add_attached_instance_info(config, module, result, lookup_attached_instance): compute_client = ComputeClient(config) try: result['boot_volume']['attached_instance_information'] = oci_utils.get_attached_instance_info( config, lookup_attached_instance, list_attachments_fn=compute_client.list_boot_volume_attachments, list_attachments_args={"boot_volume_id": result["boot_volume"]["id"], "availability_domain": result["boot_volume"]["availability_domain"], "compartment_id": result["boot_volume"]["compartment_id"]} ) except ServiceError as ex: module.fail_json(msg=ex.message)
def main(): module_args = oci_utils.get_common_arg_spec() module_args.update( dict(availability_domain=dict(type='str', required=False), compartment_id=dict(type='str', required=False), instance_id=dict(type='str', required=False), boot_volume_id=dict(type='str', required=False), boot_volume_attachment_id=dict(type='str', required=False, aliases=['id']))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=False) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) boot_volume_attachment_id = module.params['boot_volume_attachment_id'] try: if boot_volume_attachment_id is not None: result = [ to_dict( oci_utils.call_with_backoff( compute_client.get_boot_volume_attachment, boot_volume_attachment_id=boot_volume_attachment_id). data) ] else: key_list = [ "availability_domain", "compartment_id", "instance_id", "boot_volume_id" ] param_map = { k: v for (k, v) in six.iteritems(module.params) if k in key_list and v is not None } result = to_dict( oci_utils.list_all_resources( compute_client.list_boot_volume_attachments, **param_map)) except ServiceError as ex: module.fail_json(msg=ex.message) module.exit_json(boot_volume_attachments=result)
def main(): module_args = oci_utils.get_common_arg_spec() module_args.update( dict(compartment_id=dict(type='str', required=False), availability_domain=dict(type='str', required=False), instance_id=dict(type='str', required=False), vnic_attachment_id=dict(type='str', required=False, aliases=['id']))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=False, mutually_exclusive=['id', 'compartment_id']) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) compartment_id = module.params.get('compartment_id', None) id = module.params['vnic_attachment_id'] result = dict() try: if compartment_id: # filter and get only key:values that have been provided by the user key_list = ['availability_domain', "instance_id", "compartment_id"] param_map = { k: v for (k, v) in six.iteritems(module.params) if k in key_list and v is not None } inst = oci_utils.list_all_resources( compute_client.list_vnic_attachments, **param_map) result = to_dict(inst) else: inst = oci_utils.call_with_backoff( compute_client.get_vnic_attachment, vnic_attachment_id=id).data result = to_dict([inst]) except ServiceError as ex: module.fail_json(msg=ex.message) except MaximumWaitTimeExceeded as mwte: module.fail_json(msg=str(mwte)) module.exit_json(vnic_attachments=result)
def add_attached_instance_info(config, module, result, lookup_attached_instance): compute_client = ComputeClient(config) if 'volume' in result: try: result['volume'][ 'attached_instance_information'] = oci_utils.get_attached_instance_info( config, lookup_attached_instance, list_attachments_fn=compute_client.list_volume_attachments, list_attachments_args={ "volume_id": result['volume']['id'], "compartment_id": result['volume']['compartment_id'] }) except ServiceError as ex: module.fail_json(msg=ex.message)
def main(): module_args = oci_utils.get_common_arg_spec() module_args.update( dict(compartment_id=dict(type='str', required=False), availability_domain=dict(type='str', required=False), instance_id=dict(type='str', required=False, aliases=['id']))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=False, mutually_exclusive=['id', 'compartment_id']) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) compartment_id = module.params['compartment_id'] id = module.params['instance_id'] result = dict(changed=False) if compartment_id: result = list_instances(compute_client, module) else: try: inst = oci_utils.call_with_backoff(compute_client.get_instance, instance_id=id).data result = to_dict([inst]) except ServiceError as ex: module.fail_json(msg=ex.message) # For each instance in the result, add related volume_attachments and boot_volume_attachment facts try: add_volume_attachment_facts(compute_client, result) add_boot_volume_attachment_facts(compute_client, result) except ServiceError as ex: module.fail_json(msg=ex.message) module.exit_json(instances=result)
def main(): module_args = oci_utils.get_common_arg_spec() module_args.update( dict( compartment_id=dict(type='str', required=True), availability_domain=dict(type='str', required=False), )) module = AnsibleModule( argument_spec=module_args, supports_check_mode=False, ) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) compartment_id = module.params['compartment_id'] availability_domain = module.params['availability_domain'] result = dict(changed=False) try: if availability_domain: shapes = oci_utils.list_all_resources( compute_client.list_shapes, compartment_id=compartment_id, availability_domain=availability_domain) else: shapes = oci_utils.list_all_resources( compute_client.list_shapes, compartment_id=compartment_id) result['shapes'] = to_dict(shapes) except ServiceError as ex: module.fail_json(msg=ex.message) module.exit_json(shapes=result)
#from vcn import VCN #from compute import Compute #from load_balancer import LoadBalancer debug = False if debug: parser = configparser.ConfigParser() parser.read('config') config = parser.defaults() else: config = oci.config.from_file() lb_client = LoadBalancerClient(config) compute_client = ComputeClient(config) vcn_client = VirtualNetworkClient(config) def sleep(): time.sleep(1) def destroy_compute_instance(instance): print 'Destroying compute instance ...' compute_client.terminate_instance(instance.id) while True: try: if compute_client.get_instance(instance.id).data.lifecycle_state == 'TERMINATED': return sleep() except Exception as e: return def destroy_subnet(subnet): print '\tDestroying subnet ...'
def __init__(self): self.inventory = {} # Ansible Inventory self.config = None self.params = { "ini_file": os.path.join(os.path.dirname(os.path.realpath(__file__)), 'oci_inventory.ini'), "config_file": os.path.join(os.path.expanduser("~"), ".oci", "config"), "profile": "DEFAULT", "user": None, "fingerprint": None, "key_file": None, "tenancy": None, "region": None, "pass_phrase": None, "cache_dir": ".", "cache_max_age": 300, "cache_file": "./ansible-oci.cache", "compartment": None, "debug": False, "hostname_format": "public_ip", "sanitize_names": True, "replace_dash_in_names": False } self.parse_cli_args() if self.args.debug: self.params["debug"] = True self.log("Executing in debug mode.") if 'OCI_INI_PATH' in os.environ: oci_ini_file_path = os.path.expanduser( os.path.expandvars(os.environ.get('OCI_INI_PATH'))) if os.path.isfile(oci_ini_file_path): self.params["ini_file"] = oci_ini_file_path self.settings_config = configparser.ConfigParser() self.settings_config.read(self.params["ini_file"]) # Preference order: CLI args > environment variable > settings from config file. if "config_file" in self.args and getattr(self.args, "config_file") is not None: self.params['config_file'] = os.path.expanduser( self.args.config_file) elif 'OCI_CONFIG_FILE' in os.environ: self.params['config_file'] = os.path.expanduser( os.path.expandvars(os.environ.get('OCI_CONFIG_FILE'))) elif self.settings_config.has_option('oci', 'config_file'): self.params['config_file'] = os.path.expanduser( self.settings_config.get('oci', 'config_file')) if "profile" in self.args and getattr(self.args, "profile") is not None: self.params['profile'] = self.args.profile elif 'OCI_CONFIG_PROFILE' in os.environ: self.params['profile'] = os.environ.get('OCI_CONFIG_PROFILE') elif self.settings_config.has_option('oci', 'profile'): self.params['profile'] = self.settings_config.get('oci', 'profile') self.read_config() self.read_settings_config() self.read_env_vars() self.read_cli_args() self.log("Using following parameters for OCI dynamic inventory:") self.log(self.params) self.compute_client = ComputeClient(self.params) self.identity_client = IdentityClient(self.params) self.virtual_nw_client = VirtualNetworkClient(self.params) self.params['cache_file'] = os.path.join(self.params['cache_dir'], "ansible-oci.cache") if not self.args.refresh_cache and self.is_cache_valid(): self.log("Reading inventory from cache.") self.inventory = self.read_from_cache() else: self.build_inventory() self.write_to_cache(self.inventory) if self.args.host: if self.args.host in self.inventory['_meta']['hostvars']: print( json.dumps( self.inventory['_meta']['hostvars'][self.args.host], sort_keys=True, indent=2)) else: self.log( "Either the specified host does not exist or its facts cannot be retrieved." ) print({}) else: print(json.dumps(self.inventory, sort_keys=True, indent=2))
def main(): my_logger = oci_utils.get_logger("oci_instance") set_logger(my_logger) module_args = oci_utils.get_common_arg_spec(supports_wait=True) module_args.update( dict(display_name=dict(type='str', required=False, aliases=['name']), instance_id=dict(type='str', required=False), vnic_attachment_id=dict(type='str', required=False, aliases=['id']), nic_index=dict(type='int', required=False, default=0), create_vnic_details=dict(type='dict', required=False, aliases=['vnic']), state=dict(type='str', required=False, default='present', choices=['present', 'absent']))) module = AnsibleModule( argument_spec=module_args, supports_check_mode=False, mutually_exclusive=['id', 'create_vnic_details'], required_if=[('state', 'absent', ['vnic_attachment_id'])], ) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) state = module.params['state'] result = dict(changed=False) vna_id = module.params['vnic_attachment_id'] debug("VNIC attachment Id provided by user is " + str(vna_id)) try: if vna_id is not None: vna = oci_utils.get_existing_resource( compute_client.get_vnic_attachment, module, vnic_attachment_id=vna_id) if state == 'absent': if vna is not None: debug("Deleting " + vna.id) result = oci_utils.delete_and_wait( resource_type=RESOURCE_NAME, client=compute_client, get_fn=compute_client.get_vnic_attachment, kwargs_get={"vnic_attachment_id": vna_id}, delete_fn=compute_client.detach_vnic, kwargs_delete={"vnic_attachment_id": vna_id}, module=module, wait_applicable=True) else: debug("VNIC attachment " + vna_id + " already detached. So returning changed=False.") else: module.fail_json( "To delete a VNIC attachment, set state=absent") else: # Create a secondary VNIC and attach it to an instance instance_id = module.params.get("instance_id") exclude_attributes = {'display_name': True} default_attribute_values = {"nic_index": 0} compartment_id = compute_client.get_instance( instance_id=instance_id).data.compartment_id result = oci_utils.check_and_create_resource( resource_type=RESOURCE_NAME, create_fn=attach_vnic, kwargs_create={ "compute_client": compute_client, "module": module }, list_fn=compute_client.list_vnic_attachments, kwargs_list={ "compartment_id": compartment_id, "instance_id": instance_id }, module=module, model=AttachVnicDetails(), exclude_attributes=exclude_attributes, default_attribute_values=default_attribute_values) except ServiceError as ex: module.fail_json(msg=ex.message) except MaximumWaitTimeExceeded as mwte: module.fail_json(msg=str(mwte)) module.exit_json(**result)
class Compute(object): def __init__(self, config, subnet): self.config = config self.client = ComputeClient(config) self.operating_systems = self.get_operating_systems() self.subnet = subnet self.keyfile = 'private' + self.subnet.availability_domain[-1] + '.pem' self.name = self.config[ 'display_name'] + ' ' + self.subnet.availability_domain[-1] def get_operating_systems(self): operating_systems = {} images = self.client.list_images(self.config['compartment']).data for image in images: os = image.operating_system + " " + image.operating_system_version if os not in operating_systems: operating_systems[os] = image.id return operating_systems def create_metadata(self): key = rsa.generate_private_key(backend=crypto_default_backend(), public_exponent=65537, key_size=2048) self.private_key = key.private_bytes( crypto_serialization.Encoding.PEM, crypto_serialization.PrivateFormat.TraditionalOpenSSL, crypto_serialization.NoEncryption()) self.public_key = key.public_key().public_bytes( crypto_serialization.Encoding.OpenSSH, crypto_serialization.PublicFormat.OpenSSH) with open('./' + self.keyfile, 'w+') as f: os.chmod('./' + self.keyfile, 0o600) f.write(self.private_key.decode()) print 'Created private ssh key - "./' + self.keyfile + '"' metadata = {'ssh_authorized_keys': self.public_key.decode()} return metadata def launch_instance(self): print 'Creating compute instance ...' compute_details = LaunchInstanceDetails( availability_domain=self.subnet.availability_domain, compartment_id=self.config['compartment'], display_name=self.name, image_id=self.operating_systems[self.config['image_os']], shape=self.config['shape'], subnet_id=self.subnet.id, metadata=self.create_metadata()) while True: try: self.compute_instance = self.client.launch_instance( compute_details).data return except Exception as e: continue def get_vnic(self, vcn): while True: vnic_attachments = self.client.list_vnic_attachments( self.config['compartment']).data for attachment in vnic_attachments: if self.compute_instance.id == attachment.instance_id: vnic = vcn.client.get_vnic(attachment.vnic_id).data self.public_ip = vnic.public_ip self.private_ip = vnic.private_ip return def terminate_instance(self): print 'Terminating compute instance ...' self.client.terminate_instance(self.instance_id)
def main(): module_args = oci_utils.get_common_arg_spec(supports_wait=True) module_args.update( dict(instance_id=dict(type='str', required=False), state=dict(type='str', required=False, default='present', choices=['absent', 'present']), boot_volume_id=dict(type='str', required=False), boot_volume_attachment_id=dict(type='str', required=False, aliases=['id']), display_name=dict(type='str', required=False, aliases=['name']))) module = AnsibleModule( argument_spec=module_args, supports_check_mode=False, required_if=[['state', 'absent', ['boot_volume_attachment_id']], ['state', 'present', ['instance_id', 'boot_volume_id']]]) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) exclude_attributes = {'display_name': True} state = module.params['state'] if state == 'absent': result = oci_utils.delete_and_wait( resource_type=RESOURCE_NAME, client=compute_client, get_fn=compute_client.get_boot_volume_attachment, kwargs_get={ "boot_volume_attachment_id": module.params["boot_volume_attachment_id"] }, delete_fn=compute_client.detach_boot_volume, kwargs_delete={ "boot_volume_attachment_id": module.params["boot_volume_attachment_id"] }, module=module) else: instance = compute_client.get_instance( module.params["instance_id"]).data result = oci_utils.check_and_create_resource( resource_type=RESOURCE_NAME, create_fn=attach_boot_volume, kwargs_create={ "compute_client": compute_client, "module": module }, list_fn=compute_client.list_boot_volume_attachments, kwargs_list={ "availability_domain": instance.availability_domain, "compartment_id": instance.compartment_id, "instance_id": module.params['instance_id'], "boot_volume_id": module.params['boot_volume_id'] }, exclude_attributes=exclude_attributes, module=module, model=AttachBootVolumeDetails()) module.exit_json(**result)
def main(): module_args = oci_utils.get_common_arg_spec(supports_wait=True) module_args.update( dict(instance_id=dict(type='str', required=False), is_read_only=dict(type='bool', required=False, default=False), state=dict(type='str', required=False, default='present', choices=['absent', 'present']), type=dict(type='str', required=False, choices=['iscsi', 'paravirtualized']), use_chap=dict(type='bool', required=False, default=False), volume_id=dict(type='str', required=False), volume_attachment_id=dict(type='str', required=False, aliases=['id']), display_name=dict(type='str', required=False))) module = AnsibleModule( argument_spec=module_args, supports_check_mode=False, required_if=[['state', 'absent', ['volume_attachment_id']], ['state', 'present', ['instance_id', 'volume_id']]]) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) state = module.params['state'] exclude_attributes = {'display_name': True} if state == 'absent': result = oci_utils.delete_and_wait( resource_type=RESOURCE_NAME, client=compute_client, get_fn=compute_client.get_volume_attachment, kwargs_get={ "volume_attachment_id": module.params["volume_attachment_id"] }, delete_fn=compute_client.detach_volume, kwargs_delete={ "volume_attachment_id": module.params["volume_attachment_id"] }, module=module) else: compartment_id = compute_client.get_instance( module.params["instance_id"]).data.compartment_id result = oci_utils.check_and_create_resource( resource_type=RESOURCE_NAME, create_fn=attach_volume, kwargs_create={ "compute_client": compute_client, "module": module }, list_fn=compute_client.list_volume_attachments, kwargs_list={ "compartment_id": compartment_id, "instance_id": module.params['instance_id'], "volume_id": module.params['volume_id'] }, module=module, model=AttachVolumeDetails(), exclude_attributes=exclude_attributes, default_attribute_values={ "is_read_only": False, "use_chap": False }) module.exit_json(**result)
print("Instance does not exist.") def list_shapes(): data = updatedata() for r in data: print(r.display_name) # Running the program if __name__ == '__main__': """Change this to the location of your config file""" config = oci.config.from_file(file_location="<location of the config file>") computeclient = ComputeClient(config) compartment_id = config["compartment_id"] print("Hello user,") running = True while running: print("Choose one of the following 3 options.") print() print("Input : Descriptions.") print() print("1 : To scale your compute instance.") print("2 : To list shapes in your compartment.") print("Exit : To quit.") answer = input("")
def main(): my_logger = oci_utils.get_logger("oci_instance") set_logger(my_logger) module_args = oci_utils.get_taggable_arg_spec(supports_create=True, supports_wait=True) module_args.update( dict(compartment_id=dict(type='str', required=False), name=dict(type='str', required=False, aliases=['display_name']), image_id=dict(type='str', required=False, aliases=['id']), instance_id=dict(type='str', required=False), image_source_details=dict(type='dict', required=False), state=dict(type='str', required=False, default='present', choices=['present', 'absent']))) module = AnsibleModule( argument_spec=module_args, supports_check_mode=False, mutually_exclusive=['instance_id', 'image_source_details'], required_if=[('state', 'absent', ['image_id'])], ) if not HAS_OCI_PY_SDK: module.fail_json(msg='oci python sdk required for this module.') config = oci_utils.get_oci_config(module) compute_client = ComputeClient(config) state = module.params['state'] result = dict(changed=False) id = module.params.get("image_id", None) exclude_attributes = {'display_name': True, 'launch_mode': True} debug("Id is " + str(id)) if id is not None: image_resp = _get_image_from_id(compute_client, id, module) if state == 'absent': debug("Delete " + id + " requested") if image_resp.data is not None: debug("Deleting " + image_resp.data.id) result = delete_image(compute_client, id, module) else: debug("Image " + id + " already deleted.") elif state == 'present': display_name = module.params['name'] current_image = image_resp.data attrs_equal = oci_utils.are_attrs_equal( current_image, module, ["display_name", "freeform_tags", "defined_tags"]) if not attrs_equal: result = update_image(compute_client, id, display_name, module) else: result = oci_utils.check_and_create_resource( resource_type="image", create_fn=create_image, kwargs_create={ "compute_client": compute_client, "module": module }, list_fn=compute_client.list_images, kwargs_list={"compartment_id": module.params['compartment_id']}, module=module, model=CreateImageDetails(), exclude_attributes=exclude_attributes) module.exit_json(**result)