Пример #1
0
def main():
    module_args = oci_utils.get_common_arg_spec()
    module_args.update(
        dict(private_ip_id=dict(type='str', required=False, aliases=['id']),
             subnet_id=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)
    virtual_network_client = VirtualNetworkClient(config)

    private_ip_id = module.params['private_ip_id']

    try:
        if private_ip_id is not None:
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_private_ip,
                        private_ip_id=private_ip_id).data)
            ]
        else:
            result = to_dict(
                oci_utils.list_all_resources(
                    virtual_network_client.list_private_ips,
                    subnet_id=module.params['subnet_id']))
    except ServiceError as ex:
        module.fail_json(msg=ex.message)

    module.exit_json(private_ips=result)
Пример #2
0
def main():
    module_args = oci_utils.get_common_arg_spec()
    module_args.update(
        dict(vnic_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)
    virtnw_client = VirtualNetworkClient(config)

    id = module.params['vnic_id']

    result = dict()
    try:
        inst = oci_utils.call_with_backoff(virtnw_client.get_vnic,
                                           vnic_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=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 main():
    module_args = oci_utils.get_taggable_arg_spec()
    module_args.update(
        dict(hostname_label=dict(type='str', required=False),
             ip_address=dict(type='str', required=False),
             display_name=dict(type='str', required=False, aliases=['name']),
             vnic_id=dict(type='str', required=False),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['absent', 'present']),
             private_ip_id=dict(type='str', required=False, aliases=['id'])))

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=False,
                           required_if=[('state', 'absent', ['private_ip_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)
    virtual_network_client = VirtualNetworkClient(config)

    state = module.params['state']
    private_ip_id = module.params['private_ip_id']

    if state == 'absent':
        result = delete_private_ip(virtual_network_client, module)

    else:
        if private_ip_id is not None:
            result = update_private_ip(virtual_network_client, module)
        else:
            # Exclude ip_address & display_name when matching private_ips if they are not explicitly specified by user.
            exclude_attributes = {'display_name': True, 'ip_address': True}
            subnet_id = oci_utils.call_with_backoff(
                virtual_network_client.get_vnic,
                vnic_id=module.params['vnic_id']).data.subnet_id
            result = oci_utils.check_and_create_resource(
                resource_type='private_ip',
                create_fn=create_private_ip,
                kwargs_create={
                    'virtual_network_client': virtual_network_client,
                    'module': module
                },
                list_fn=virtual_network_client.list_private_ips,
                kwargs_list={
                    "vnic_id": module.params['vnic_id'],
                    "subnet_id": subnet_id
                },
                module=module,
                model=CreatePrivateIpDetails(),
                exclude_attributes=exclude_attributes)

    module.exit_json(**result)
Пример #5
0
def main():
    module_args = oci_utils.get_taggable_arg_spec(supports_create=True,
                                                  supports_wait=True)
    module_args.update(
        dict(cidr_block=dict(type='str', required=False),
             compartment_id=dict(type='str', required=False),
             display_name=dict(type='str', required=False, aliases=['name']),
             dns_label=dict(type='str', required=False),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['absent', 'present']),
             vcn_id=dict(type='str', required=False, aliases=['id'])))

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=False,
                           mutually_exclusive=[['compartment_id', 'vcn_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)
    virtual_network_client = VirtualNetworkClient(config)
    exclude_attributes = {'display_name': True, 'dns_label': True}
    state = module.params['state']
    vcn_id = module.params['vcn_id']

    if state == 'absent':
        if vcn_id is not None:
            result = delete_vcn(virtual_network_client, module)
        else:
            module.fail_json(
                msg="Specify vcn_id with state as 'absent' to delete a VCN.")

    else:
        if vcn_id is not None:
            result = update_vcn(virtual_network_client, module)
        else:
            result = oci_utils.check_and_create_resource(
                resource_type='vcn',
                create_fn=create_vcn,
                kwargs_create={
                    'virtual_network_client': virtual_network_client,
                    'module': module
                },
                list_fn=virtual_network_client.list_vcns,
                kwargs_list={
                    'compartment_id': module.params['compartment_id']
                },
                module=module,
                model=CreateVcnDetails(),
                exclude_attributes=exclude_attributes)

    module.exit_json(**result)
def main():
    module_args = oci_utils.get_common_arg_spec()
    module_args.update(
        dict(compartment_id=dict(type='str', required=False),
             subnet_id=dict(type='str', required=False),
             vcn_id=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)
    virtual_network_client = VirtualNetworkClient(config)

    subnet_id = module.params['subnet_id']
    vcn_id = module.params['vcn_id']
    compartment_id = module.params['compartment_id']
    result = []

    if subnet_id is not None:
        try:
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_subnet,
                        subnet_id=subnet_id).data)
            ]
        except ServiceError as ex:
            module.fail_json(msg=ex.message)
    elif compartment_id is not None and vcn_id is not None:
        try:
            result = to_dict(
                oci_utils.list_all_resources(
                    virtual_network_client.list_subnets,
                    compartment_id=compartment_id,
                    vcn_id=vcn_id))
        except ServiceError as ex:
            module.fail_json(msg=ex.message)
    else:
        module.fail_json(
            msg=
            "Specify a compartment_id and a vcn_id to get all the subnets in the compartment and the \
                            VCN or a subnet_id to retrieve a specific subnet")

    module.exit_json(subnets=result)
#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 ...' 
    vcn_client.delete_subnet(subnet.id)
Пример #8
0
    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))
Пример #9
0
 def __init__(self, config):
     self.config = config
     self.client = VirtualNetworkClient(config)
     self.subnets = []
     self.route_rules = []
     self.security_rules = []
Пример #10
0
class VCN(object):

    def __init__(self, config):
        self.config = config
        self.client = VirtualNetworkClient(config)
        self.subnets = []
        self.route_rules = []
        self.security_rules = []

    def create_vcn(self):
        print 'Creating VCN ...' 
        vcn_details = CreateVcnDetails(
            cidr_block = self.config['vcn_cidr'],
            compartment_id = self.config['compartment'],
            display_name = self.config['display_name']
        )
        self.vcn_config = self.client.create_vcn(vcn_details).data

    def create_gateway(self):
        gateway_details = CreateInternetGatewayDetails(
            compartment_id = self.config['compartment'],
            is_enabled = True,
            vcn_id = self.vcn_config.id
        )
        self.gateway = self.client.create_internet_gateway(gateway_details).data

    def create_route_rules(self):
        route_rule = RouteRule(
            cidr_block = self.config['rt_cidr'],
            network_entity_id = self.gateway.id
        )
        self.route_rules.append(route_rule)
        route_table_details = UpdateRouteTableDetails(route_rules=self.route_rules)
        self.default_route_table = self.client.update_route_table(
            rt_id = self.vcn_config.default_route_table_id,
            update_route_table_details = route_table_details
        )

    def create_subnet(self, ad):
        cidr = '10.0.'+str(int(ad[-1])-1)+'.0/24'
        print 'Creating subnet with cidr: %s' % (cidr)
        subnet_details = CreateSubnetDetails(
            availability_domain = self.config[ad],
            cidr_block = cidr,
            compartment_id = self.config['compartment'],
            vcn_id = self.vcn_config.id
        )
        try: 
            self.subnets.append(self.client.create_subnet(subnet_details).data)
        except Exception as e:
            pass
        finally:
            pass
        while True:
            try:
                subnet = self.client.get_subnet(subnet_id=self.subnets[-1].id).data
                if subnet.lifecycle_state == 'AVAILABLE':
                    return
                else: 
                    continue
            except Exception as e:
                continue
            finally:
                return


    def create_security_rules(self):
        security_list = self.client.get_security_list(security_list_id=self.vcn_config.default_security_list_id).data
        self.ingress_rules = security_list.ingress_security_rules
        self.egress_rules = security_list.egress_security_rules
        dest_port_range = PortRange(min=8000, max=8999)
        tcp_options = TcpOptions(destination_port_range=dest_port_range)
        security_rule = IngressSecurityRule(
            protocol = '6',
            source = '0.0.0.0/0',
            tcp_options = tcp_options
        )
        self.ingress_rules.append(security_rule)
        security_list_details = UpdateSecurityListDetails(
            ingress_security_rules=self.ingress_rules,
            egress_security_rules=self.egress_rules
        )
        self.default_security_list = self.client.update_security_list(
            security_list_id = self.vcn_config.default_security_list_id,
            update_security_list_details = security_list_details
        )
Пример #11
0
def main():
    my_logger = oci_utils.get_logger("oci_instance")
    set_logger(my_logger)

    module_args = oci_utils.get_common_arg_spec()
    module_args.update(
        dict(name=dict(type='str', required=False, aliases=['display_name']),
             vnic_id=dict(type='str', required=False, aliases=['id']),
             hostname_label=dict(type='str', required=False),
             skip_source_dest_check=dict(type='bool',
                                         required=False,
                                         default=False),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['present'])))

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False,
        required_if=[('state', 'present', ['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)
    virtnetwork_client = VirtualNetworkClient(config)

    result = dict(changed=False)

    id = module.params['id']
    debug("VNIC Id provided by user is " + str(id))

    try:
        vnic = oci_utils.call_with_backoff(virtnetwork_client.get_vnic,
                                           vnic_id=id).data
        if vnic is not None:
            name = module.params['name']
            hostname_label = module.params['hostname_label']
            skip_source_dest_check = module.params['skip_source_dest_check']
            if not oci_utils.are_attrs_equal(vnic, module,
                                             vnic.attribute_map.keys()):
                debug("Need to update VNIC " + str(id))

                uvd = UpdateVnicDetails()
                uvd.skip_source_dest_check = skip_source_dest_check
                uvd.hostname_label = hostname_label
                uvd.display_name = name

                oci_utils.call_with_backoff(virtnetwork_client.update_vnic,
                                            vnic_id=id,
                                            update_vnic_details=uvd)
                result['changed'] = True
        resp = oci_utils.call_with_backoff(virtnetwork_client.get_vnic,
                                           vnic_id=id)
        result['vnic'] = to_dict(resp.data)
    except ServiceError as ex:
        module.fail_json(msg=ex.message)

    module.exit_json(**result)
Пример #12
0
def main():
    module_args = oci_utils.get_common_arg_spec()
    module_args.update(
        dict(public_ip_id=dict(type='str', required=False, aliases=['id']),
             private_ip_id=dict(type='str', required=False),
             ip_address=dict(type='str', required=False),
             scope=dict(type='str',
                        required=False,
                        choices=["REGION", "AVAILABILITY_DOMAIN"]),
             compartment_id=dict(type='str', required=False),
             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)
    virtual_network_client = VirtualNetworkClient(config)

    public_ip_id = module.params['public_ip_id']

    try:
        if public_ip_id is not None:
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_public_ip,
                        public_ip_id=public_ip_id).data)
            ]
        elif module.params['private_ip_id'] is not None:
            pvt_ip_id_details = GetPublicIpByPrivateIpIdDetails(
                private_ip_id=module.params['private_ip_id'])
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_public_ip_by_private_ip_id,
                        get_public_ip_by_private_ip_id_details=pvt_ip_id_details
                    ).data)
            ]
        elif module.params['ip_address'] is not None:
            ip_address_details = GetPublicIpByIpAddressDetails(
                ip_address=module.params['ip_address'])
            result = [
                to_dict(
                    oci_utils.call_with_backoff(
                        virtual_network_client.get_public_ip_by_ip_address,
                        get_public_ip_by_ip_address_details=ip_address_details
                    ).data)
            ]
        elif module.params['scope'] is not None:
            list_args = {
                'scope': module.params['scope'],
                'compartment_id': module.params['compartment_id']
            }
            if module.params['availability_domain'] is not None:
                list_args['availability_domain'] = module.params[
                    'availability_domain']

            result = to_dict(
                oci_utils.list_all_resources(
                    virtual_network_client.list_public_ips, **list_args))
        else:
            module.fail_json(
                msg=
                "Specify scope along with compartment_id to list all public IPs or one of"
                "public_ip_id/private_ip_id/ip_address.")
    except ServiceError as ex:
        module.fail_json(msg=ex.message)

    module.exit_json(public_ips=result)
Пример #13
0
def main():
    module_args = oci_utils.get_taggable_arg_spec(supports_create=True,
                                                  supports_wait=True)
    module_args.update(
        dict(availability_domain=dict(type='str', required=False),
             cidr_block=dict(type='str', required=False),
             compartment_id=dict(type='str', required=False),
             dhcp_options_id=dict(type='str', required=False),
             display_name=dict(type='str', required=False, aliases=['name']),
             dns_label=dict(type='str', required=False),
             prohibit_public_ip_on_vnic=dict(type='bool',
                                             required=False,
                                             default=False),
             route_table_id=dict(type='str', required=False),
             security_list_ids=dict(type='list', required=False),
             subnet_id=dict(type='str', required=False, aliases=['id']),
             state=dict(type='str',
                        required=False,
                        default='present',
                        choices=['absent', 'present']),
             vcn_id=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)
    virtual_network_client = VirtualNetworkClient(config)
    exclude_attributes = {
        'display_name': True,
        'dns_label': True,
        'dhcp_options_id': True
    }
    state = module.params['state']
    subnet_id = module.params['subnet_id']

    if state == 'absent':
        if subnet_id is not None:
            result = delete_subnet(virtual_network_client, module)
        else:
            module.fail_json(
                msg=
                "Specify subnet_id with state as 'absent' to delete a subnet.")

    else:
        if subnet_id is not None:
            result = update_subnet(virtual_network_client, module)
        else:
            vcn = oci_utils.call_with_backoff(
                virtual_network_client.get_vcn,
                vcn_id=module.params["vcn_id"]).data

            default_attribute_values = {
                "dhcp_options_id": vcn.default_dhcp_options_id,
                "prohibit_public_ip_on_vnic": False,
                "route_table_id": vcn.default_route_table_id,
                "security_list_ids": [vcn.default_security_list_id]
            }

            result = oci_utils.check_and_create_resource(
                resource_type='subnet',
                create_fn=create_subnet,
                kwargs_create={
                    'virtual_network_client': virtual_network_client,
                    'module': module
                },
                list_fn=virtual_network_client.list_subnets,
                kwargs_list={
                    'compartment_id': module.params['compartment_id'],
                    'vcn_id': module.params['vcn_id']
                },
                module=module,
                model=CreateSubnetDetails(),
                exclude_attributes=exclude_attributes,
                default_attribute_values=default_attribute_values)

    module.exit_json(**result)
def main():
    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),
        lifetime=dict(type='str', required=False, choices=['EPHEMERAL', 'RESERVED']),
        display_name=dict(type='str', required=False, aliases=['name']),
        state=dict(type='str', required=False, default='present', choices=['absent', 'present']),
        private_ip_id=dict(type='str', required=False),
        public_ip_id=dict(type='str', required=False, aliases=['id'])
    ))

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=False,
        required_if=[
            ('state', 'absent', ['public_ip_id']),
            ('lifetime', 'EPHEMERAL', ['private_ip_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)
    virtual_network_client = VirtualNetworkClient(config)

    state = module.params['state']
    public_ip_id = module.params['public_ip_id']

    if state == 'absent':
        result = delete_public_ip(virtual_network_client, module)

    else:
        if public_ip_id is not None:
            result = update_public_ip(virtual_network_client, module)
        else:
            exclude_attributes = {'display_name': True}
            # If the user desired lifetime of the public IP to be created is RESERVED, then use SCOPE as REGION for
            # making a call to list all the public IPs else use SCOPE as AVAILABILITY_DOMAIN.
            if module.params["lifetime"] == "RESERVED":
                kwargs_list = {'scope': "REGION",
                               'compartment_id': module.params['compartment_id']}
            else:
                # To list ephemeral public IPs, availability domain parameter is required. An ephemeral public IP is
                # always in the same Availability Domain as the private IP it's assigned to. Get the AD from private_ip.
                pvt_ip_ad = virtual_network_client.get_private_ip(
                    module.params["private_ip_id"]).data.availability_domain
                kwargs_list = {'scope': "AVAILABILITY_DOMAIN",
                               'compartment_id': module.params['compartment_id'],
                               'availability_domain': pvt_ip_ad}
            result = oci_utils.check_and_create_resource(resource_type='public_ip',
                                                         create_fn=create_public_ip,
                                                         kwargs_create={
                                                             'virtual_network_client': virtual_network_client,
                                                             'module': module},
                                                         list_fn=virtual_network_client.list_public_ips,
                                                         kwargs_list=kwargs_list,
                                                         module=module,
                                                         model=CreatePublicIpDetails(),
                                                         exclude_attributes=exclude_attributes
                                                         )
    module.exit_json(**result)