Beispiel #1
0
    def detach_volume(self, instance, attachment):
        """Detach volume from an instance

        :param instance: Instance name or ID
        :type instance: str
        :param attachment: Volume attachement name or ID
        :type attachment: str
        """
        try:
            instance_info = self.get_instance(instance)
            if "errors" in instance_info:
                return instance_info

            attachment_info = self.get_instance_volume_attachment(
                instance_info["id"], attachment)
            if "errors" in attachment_info:
                return attachment_info

            path = ("/v1/instances/{}/volume_attachments/{}"
                    "?version={}&generation={}".format(instance_info["id"],
                                                       attachment_info["id"],
                                                       self.cfg["version"],
                                                       self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            if data["response"].status != 204:
                return data["data"]

            return resource_deleted()

        except Exception as error:
            print("Error detaching volume with attachment {} from instance"
                  " {}. {}".format(attachment, instance, error))
            raise
Beispiel #2
0
    def get_instance_interface_by_id(self, instance, id):
        """Retrieve specific network interface for a specific instance by ID

        :param instance: Instance name or ID
        :type instance: str
        :param id: Interface ID
        :type id: str
        :return: Instance's interface information
        :rtype: dict
        """
        instance_info = self.get_instance(instance)
        if "errors" in instance_info:
            return instance_info

        try:
            path = ("/v1/instances/{}/network_interfaces/{}?version={}"
                    "&generation={}".format(instance_info["id"], id,
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching network interface {} for instance"
                  " {}. {}".format(instance, id, error))
            raise
Beispiel #3
0
    def delete_binding(self, binding):
        """Delete resource binding

        :param binding: Resource binding name or ID
        :type binding: str
        :return: Delete status
        :rtype: resource_deleted()
        """
        try:
            # Check if binding exists
            binding_info = self.get_resource_binding(binding)
            if "errors" in binding_info:
                return binding_info

            # Connect to api endpoint resource_bindings
            path = ("/v2/resource_bindings/{}".format(binding_info["id"]))

            data = qw("rg", "DELETE", path, headers())

            # Return data
            if data["response"].status != 204:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting resource binding {}. {}".format(
                binding, error))
            raise
    def delete_volume(self, volume):
        """Delete volume

        :param volume: Volume name or ID
        :type volume: str
        :return: Delete status
        :rtype: resource_deleted()
        """
        # Check if volume exists and get information
        volume_info = self.get_volume(volume)
        if "errors" in volume_info:
            return volume_info

        try:
            # Connect to api endpoint for volumes
            path = ("/v1/volumes/{}?version={}&generation={}".format(
                volume_info["id"], self.cfg["version"],
                self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            # Return data
            if data["response"].status != 204:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting volume {}. {}".format(volume, error))
            raise
    def get_resource_instance_by_guid(self, guid):
        """Retrieve specific resoure instance by GUID

        :param guid: Resource instance GUID
        :ẗype guid: str
        :return: Resource instance information
        :rtype: dict
        """
        try:
            # Connect to api endpoint for resource instances
            path = ("/v2/resource_instances/{}".format(quote(guid)))

            result = qw("rg", "GET", path, headers())["data"]

            # Needed because API doens't return the same output as other API.
            if "status_code" in result:
                if result["status_code"] == 404:
                    return resource_not_found()
                return result

            return result
        except Exception as error:
            print("Error fetching resource instance with ID {}. {}".format(
                guid, error))
            raise
    def delete_resource_instance(self, instance):
        """Delete a resource instance

        :param instance: The resource instance name or ID
        :type instance: str
        :return: Deletion status
        :rtype: resource_deleted()
        """
        try:
            instance_info = self.get_resource_instance(instance)
            if "errors" in instance_info:
                return instance_info

            # Connect to api endpoint for resource_instances
            path = ("/v2/resource_instances/{}".format(instance_info['guid']))

            data = qw("rg", "DELETE", path, headers())

            # Return data
            if data["response"].status != 204:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting resource instance. {}".format(error))
    def get_lb_pool_by_id(self, lb, id):
        """Retrieve specific pool from load balancer by ID

        :param lb: Load balancer name or ID
        :type lb: str
        :param id: Pool ID
        :type id: str
        :return: Pool information
        :rtype: dict
        """
        try:
            # Retrieve load balancer information
            lb_info = self.get_lb(lb)
            if "errors" in lb_info:
                return lb_info

            # Connect to api endpoint for load_balancers
            path = ("/v1/load_balancers/{}/pools/{}?version={}"
                    "&generation={}".format(lb_info["id"], id,
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching pool with ID {} from load balancer"
                  " {}. {}".format(id, lb, error))
            raise
    def get_lb_pool_members(self, lb, pool):
        """Retrieve pools from loadbalancer

        :param lb: Load balancer name or ID
        :type lb: str
        :param pool: Pool name or ID
        :type pool: str
        :return: List of members of a pool
        :rtype: list
        """
        try:
            # Retrieve load balancer information
            lb_info = self.get_lb(lb)
            if "errors" in lb_info:
                return lb_info

            # Retrieve pool information
            pool_info = self.get_lb_pool(lb, pool)
            if "errors" in pool_info:
                return pool_info

            # Connect to api endpoint for load_balancers
            path = ("/v1/load_balancers/{}/pools/{}/members?version={}"
                    "&generation={}".format(lb_info["id"], pool_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching members from pool {} for load balancer"
                  " {}. {}".format(pool, lb, error))
            raise
    def get_lb_listener_policy_by_id(self, lb, listener, id):
        """Retrieve specific policy from listener by ID

        :param lb: Load balancer name or ID
        :type lb: str
        :param listener: Listener port or ID
        :type listener: str
        :param id: Policy ID
        :type id: str
        :return: Listerner information
        :rtype: dict
        """
        try:
            # Connect to api endpoint for load_balancers
            path = ("/v1/load_balancers/{}/listeners/{}/policies/{}?version={}"
                    "&generation={}".format(lb, listener, id,
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching policy with ID {} from listener {}"
                  " on load balancer {}. {}".format(id, listener, lb, error))
            raise
    def get_lb_listener_policy_rule(self, lb, listener, policy, rule):
        """Retrieve specific rule from listener's policy

        :param lb: Load balancer name or ID
        :type lb: str
        :param listener: Listener port or ID
        :type listener: str
        :param policy: Policy name or ID
        :type policy: str
        :param rule: Rule ID
        :type rule: str
        :return: Rule information
        :rtype: dict
        """
        try:
            # Connect to api endpoint for load_balancers
            path = ("/v1/load_balancers/{}/listeners/{}/policies/{}/rules/{}"
                    "?version={}&generation={}".format(lb, listener, policy,
                                                       rule,
                                                       self.cfg["version"],
                                                       self.cfg["generation"]))

            # Return data
            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching rule with ID {} in policy {} from listener"
                  " {} on load balancer {}. {}".format(id, policy, listener,
                                                       lb, error))
            raise
    def get_lb_listener_policies(self, lb, listener):
        """Retrieve policies for specific listeners

        :param lb: Load balancer name or ID
        :type lb: str
        :param listener: Listener port or ID
        :type listener: str
        :return: List of policies
        :rtype: list
        """
        try:
            # Retrieve load balancer information
            lb_info = self.get_lb(lb)
            if "errors" in lb_info:
                return lb_info

            # Retrieve listener information
            listener_info = self.get_lb_listener(lb, listener)
            if "errors" in listener_info:
                return listener_info

            # Connect to api endpoint for load_balancers
            path = ("/v1/load_balancers/{}/listeners/{}/policies?version={}"
                    "&generation={}".format(lb_info["id"], listener_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching policies for listeners {} on load balancer"
                  " {}. {}".format(listener, lb, error))
            raise
    def delete_lb(self, lb):
        """Delete load balancer

        :param lb: Load balancer name or ID
        :type lb: str
        :return: Delete status
        :rtype: dict
        """
        # Check if load balancer exists
        lb_info = self.get_lb(lb)
        if "errors" in lb_info:
            return lb_info

        try:
            # Connect to api endpoint for load_balancers
            path = ("/v1/load_balancers/{}?version={}&generation={}".format(
                lb_info["id"], self.cfg["version"], self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            # Return data
            if data["response"].status != 204:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting load balancer {}. {}".format(lb, error))
            raise
    def get_lb_stats(self, lb):
        """Retrieve statistics for specific load balancer

        :param lb: Load balancer name or ID
        :type lb: str
        :return: Load balancer statistics
        :rtype: dict
        """
        try:
            # Retrieve load balancer information
            lb_info = self.get_lb(lb)
            if "errors" in lb_info:
                return lb_info

            # Connect to api endpoint for load_balancers
            path = ("/v1/load_balancers/{}/statistics/?version={}"
                    "&generation={}".format(lb_info["id"], self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching statistics for load balancer {}. {}".format(
                lb, error))
            raise
Beispiel #14
0
    def delete_image(self, image):
        """Delete image

        :param image: Image name or ID
        :type image: str
        :return: Delete status
        :rtype: dict
        """
        try:
            # Check if image exists
            image_info = self.get_image_by_name(image)
            if "errors" in image_info:
                return image_info

            # Connect to api endpoint for images
            path = ("/v1/images/{}?version={}&generation={}".format(
                image_info["id"], self.cfg["version"], self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            # Return data
            if data["response"].status != 202:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting image with name {}. {}".format(image, error))
            raise
Beispiel #15
0
    def get_instance_interface_fips(self, instance, interface):
        """Retrieve floating IPs attached to a network interface for a
        specific instance

        :param instance: Instance name or ID
        :type instance: str
        :param interface: Interface name or ID
        :type interface: str
        :return: Floating IP list attached to an interface
        :rtype: list
        """
        instance_info = self.get_instance(instance)
        if "errors" in instance_info:
            return instance_info

        interface_into = self.get_instance_interface(instance_info["id"],
                                                     interface)
        if "errors" in interface_into:
            return interface_into

        try:
            path = ("/v1/instances/{}/network_interfaces/{}/floating_ips"
                    "?version={}&generation={}".format(instance_info["id"],
                                                       interface_into["id"],
                                                       self.cfg["version"],
                                                       self.cfg["generation"]))

            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching floating IPs attached to network interface"
                  " {} for instance {}. {}".format(interface, instance, error))
            raise
Beispiel #16
0
    def delete_role(self, role):
        """Delete role

        :param role: Role name or ID
        :type role: str
        :return: Deletion status
        :rtype: dict
        """
        # Check if role exists and get information
        role_info = self.get_role(role)
        if "errors" in role_info:
            return role_info

        try:
            # Connect to api endpoint for roles
            path = ("/v1/roles/{}".format(role_info["id"]))

            data = qw("auth", "DELETE", path, headers())

            # Return data
            if data["response"].status != 204:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting polirolecy {}. {}".format(role, error))
Beispiel #17
0
    def get_vpn_gateway_connections(self, gateway):
        """Retrieve connections for a VPN gateway

        :param gateway: VPN gateway name or ID
        :type gateway: str
        :return: List of connections
        :rtype: list
        """
        # Retrieve gateway information by name to get the ID
        gateway_info = self.get_vpn_gateway(gateway)
        if "errors" in gateway_info:
            return gateway_info

        try:
            # Connect to api endpoint for vpn_gateways
            path = ("/v1/vpn_gateways/{}/connections?version={}"
                    "&generation={}".format(gateway_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching connections for VPN gateway {}. {}".format(
                gateway, error))
            raise
Beispiel #18
0
    def delete_gateway(self, gateway):
        """Delete VPN gateway

        :param gateway: VPN gateway name or ID
        :type gateway: str
        :return: Delete status
        :rtype: dict
        """
        # Check if gateway exists
        gateway_info = self.get_vpn_gateway(gateway)
        if "errors" in gateway_info:
            return gateway_info

        try:
            # Connect to api endpoint for vpn_gateways
            path = ("/v1/vpn_gateways/{}?version={}&generation={}".format(
                gateway_info["id"], self.cfg["version"],
                self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            # Return data
            if data["response"].status != 202:
                return data

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting VPN gateway {}. {}".format(gateway, error))
            raise
Beispiel #19
0
    def get_ipsec_policy_connections(self, policy):
        """Retrieve connections for an IPsec policy

        :param policy: IPsec policy name or ID
        :type policy: str
        :return: Connections information
        :rtype: dict
        """
        try:
            # Retrieve policy information by name to get the ID
            policy_info = self.get_ipsec_policy(policy)
            if "errors" in policy_info:
                return policy_info

            # Connect to api endpoint for ipsec_policies
            path = ("/v1/ipsec_policies/{}/connections?version={}"
                    "&generation={}".format(policy_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            return qw("iaas", "GET", path, headers())["data"]

        except Exception as error:
            print("Error fetching connection for IPsec policy {}. {}".format(
                policy, error))
            raise
Beispiel #20
0
    def delete_ipsec_policy(self, policy):
        """Delete IPsec policy

        :param policy: IPsec policy name or ID
        :type policy: str
        :return: Delete status
        :rtype: dict
        """
        # Check if IPsec policy exists
        policy_info = self.get_ipsec_policy(policy)
        if "errors" in policy_info:
            return policy_info

        try:
            # Connect to api endpoint for ipsec_policies
            path = ("/v1/ipsec_policies/{}?version={}&generation={}".format(
                policy_info["id"], self.cfg["version"],
                self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            # Return data
            if data["response"].status != 204:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting IPsec policy {}. {}".format(policy, error))
            raise
Beispiel #21
0
    def delete_key(self, key):
        """Delete key

        :param key: Key name or ID
        :type key: str
        :return: Delete status
        :rtype: dict
        """
        try:
            # Check if key exists
            key_info = self.get_key(key)
            if "errors" in key_info:
                return key_info

            # Connect to api endpoint for keys
            path = ("/v1/keys/{}?version={}&generation={}".format(
                key_info["id"], self.cfg["version"], self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            # Return data
            if data["response"].status != 204:
                return data["data"]

            # Return status
            return resource_deleted()

        except Exception as error:
            print("Error deleting key {}. {}".format(key, error))
            raise
Beispiel #22
0
    def delete_instance_interface(self, instance, interface):
        """Delete interface from instance

        :param instance: Instance name or ID
        :type instance: str
        :param interface: Interface name or ID
        :type interface: str
        :return: Delete status
        :rtype: dict
        """
        try:
            instance_info = self.get_instance(instance)
            if "errors" in instance_info:
                return instance_info

            interface_info = self.get_instance_interface(interface)
            if "errors" in interface_info:
                return interface_info

            path = ("/v1/instances/{}/network_interfaces/{}?version={}"
                    "&generation={}".format(instance_info["id"],
                                            interface_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            data = qw("iaas", "DELETE", path, headers())

            if data["response"].status != 204:
                return data["data"]

            return resource_deleted()

        except Exception as error:
            print("Error deleting instance {}. {}".format(instance, error))
            raise
Beispiel #23
0
    def create_security_group(self, **kwargs):
        """Create security group

        :param name: The user-defined name for this security group
        :type name: str, optional
        :param resource_group: The resource group to use
        :type security_group: str, optional
        :param vpc: The VPC this security group is to be a part of
        :type vpc: str
        :param rules: Array of rule prototype objects for rules to be created
            for this security group
        :type rules: list, optional
        """
        args = ["vpc"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'name': kwargs.get('name'),
            'resource_group': kwargs.get('resource_group'),
            'vpc': kwargs.get('vpc'),
            'rules': kwargs.get('rules'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if value is not None:
                if key == "vpc":
                    vpc_info = self.vpc.get_vpc(args["vpc"])
                    if "errors" in vpc_info:
                        return vpc_info
                    payload["vpc"] = {"id": vpc_info["id"]}
                elif key == "resource_group":
                    rg_info = self.rg.get_resource_group(
                        args["resource_group"])
                    if "errors" in rg_info:
                        return rg_info
                    payload["resource_group"] = {"id": rg_info["id"]}
                elif key == "rules":
                    rs = []
                    for sg_rules in args["rules"]:
                        rs.append(sg_rules)
                    payload["rules"] = rs
                else:
                    payload[key] = value

        try:
            # Connect to api endpoint for security_groups
            path = ("/v1/security_groups?version={}&generation={}".format(
                self.cfg["version"], self.cfg["generation"]))

            # Return data
            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating security group. {}".format(error))
            raise
    def add_permitted_network(self, **kwargs):
        """Add permitted network to DNS zone

        :param dns_zone: DNS zone name
        :type dns_zone: str
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        :param vpc: The allowed VPC name or ID
        :type vpc: str
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance', 'vpc']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'dns_zone': kwargs.get('dns_zone'),
            'vpc': kwargs.get('vpc'),
            'resource_instance': kwargs.get('resource_instance'),
        }

        # get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            args['resource_instance'])
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        # get vpc crn
        temp_vpc = self.vpc.get_vpc(args["vpc"])
        if "errors" in temp_vpc:
            return temp_vpc
        vpc_crn = temp_vpc["crn"]

        # Get zone ID
        zone_id = self.get_dns_zone_id(
            dns_zone=args['dns_zone'],
            resource_instance=resource_instance_guid)
        if "errors" in zone_id:
            return zone_id

        payload = {}

        # Construct payload
        payload["type"] = "vpc"
        payload["permitted_network"] = {}
        payload["permitted_network"]["vpc_crn"] = vpc_crn

        try:
            # Connect to api endpoint for permitted network
            path = ("/v1/instances/{}/dnszones/{}/permitted_networks").format(
                resource_instance_guid, zone_id)

            return qw("dns", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error adding permitted network. {}".format(error))
            raise
Beispiel #25
0
    def create_address_prefix(self, **kwargs):
        """Create address prefix

        :param vpc: VPC name or ID
        :type vpc: str
        :param name: The user-defined name for this address prefix
        :type name: str, optional
        :param cidr: The CIDR block for this address prefix
        :type cidr: str
        :param is_default: Indicates whether this is the default prefix for
            this zone in this VPC
        :type is_default: bool, optional
        :param zone: The zone this address prefix is to belong to
        :type zone: str
        :return: Address prefix information
        :rtype: dict
        """
        args = ["vpc", "cidr", "zone"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'vpc': kwargs.get('vpc'),
            'name': kwargs.get('name'),
            'cidr': kwargs.get('cidr'),
            'is_default': kwargs.get('is_default', False),
            'zone': kwargs.get('zone'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if key != "vpc" and value is not None:
                if key == "zone":
                    payload["zone"] = {"name": args["zone"]}
                else:
                    payload[key] = value

        # Check if VPC exists and get information
        vpc_info = self.get_vpc(args['vpc'])
        if "errors" in vpc_info:
            return vpc_info

        try:
            # Connect to api endpoint for vpcs
            path = ("/v1/vpcs/{}/address_prefixes?version={}"
                    "&generation={}".format(vpc_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating address prefix in VPC {}. {}".format(
                args['vpc'], error))
            raise
Beispiel #26
0
    def create_ike_policy(self, **kwargs):
        """Create IKE policy

        :param name: The user-defined name for this IKE policy
        :type name: str, optional
        :param resource_group: The resource group to use
        :type resource_group: str, optional
        :param authentication_algorithm: The authentication algorithm
        :type authentication_algorithm: str
        :param dh_group: The Diffie-Hellman group
        :type dh_group: str
        :param encryption_algorithm: The encryption algorithm
        :type encryption_algorithm: str
        :param ike_version: The IKE protocol version
        :type ike_version: int
        :param key_lifetime: The key lifetime in seconds
        :type key_lifetime: int, optional
        """
        args = ["authentication_algorithm", "dh_group",
                "encryption_algorithm", "ike_version"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'name': kwargs.get('name'),
            'resource_group': kwargs.get('resource_group'),
            'authentication_algorithm': kwargs.get('authentication_algorithm'),
            'dh_group': kwargs.get('dh_group'),
            'encryption_algorithm': kwargs.get('encryption_algorithm'),
            'ike_version': kwargs.get('ike_version'),
            'key_lifetime': kwargs.get('key_lifetime'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if value is not None:
                if key == "resource_group":
                    rg_info = self.rg.get_resource_group(
                        args["resource_group"])
                    if "errors" in rg_info:
                        return rg_info
                    payload["resource_group"] = {"id": rg_info["id"]}
                else:
                    payload[key] = value

        try:
            # Connect to api endpoint for ike_policies
            path = ("/v1/ike_policies?version={}&generation={}".format(
                self.cfg["version"], self.cfg["generation"]))

            # Return data
            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating IKE policy. {}".format(error))
            raise
    def get_dns_zone_by_name(self, **kwargs):
        """Get DNS zone by name

        :param dns_zone: DNS zone name to query
        :type dns_zone: str
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        :return: DNS zone information
        :rtype: dict
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'dns_zone': kwargs.get('dns_zone'),
            'resource_instance': kwargs.get('resource_instance'),
        }

        # get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            args['resource_instance'])
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        try:
            # Connect to api endpoint for dns zones
            path = ("/v1/instances/{}/dnszones").format(resource_instance_guid)

            dns_zones = qw("dns", "GET", path, headers())["data"]

            if "errors" in dns_zones or not dns_zones:
                return ({
                    "errors": [{
                        "code": "not_found",
                        "message": "No dns zones found."
                    }]
                })

            # Find the existing domain matching the query
            for dns_zone in dns_zones['dnszones']:
                if dns_zone["name"] == args['dns_zone']:
                    return dns_zone

            # Return error message if no existing domain matches the query
            return ({
                "errors": [{
                    "code": "not_found",
                    "message": "No dns zone found."
                }]
            })

        except Exception as error:
            print("Error creating dns zone. {}".format(error))
            raise
Beispiel #28
0
    def create_instance_interface(self, **kwargs):
        """Create instance interface

        :param instance: The instance name or ID
        :type instance: str
        :param subnet: The associated subnet name or ID
        :type subnet: str
        :param primary_ipv4_address: The primary IPv4 address
        :type primary_ipv4_address: str, optional
        :param security_groups: Collection of security groups
        :type security_groups: str, optional
        """
        args = ["instance", "subnet"]
        check_args(args, **kwargs)

        args = {
            'instance': kwargs.get('instance'),
            'subnet': kwargs.get('forsubnetce'),
            'primary_ipv4_address': kwargs.get('primary_ipv4_address'),
            'security_groups': kwargs.get('security_groups'),
        }

        instance_info = self.get_instance(args["instance"])
        if "errors" in instance_info:
            return instance_info

        subnet_info = self.subnet.get_subnet(args["subnet"])
        if "errors" in subnet_info:
            return subnet_info

        payload = {}
        for key, value in args.items():
            if key != "instance" and value is not None:
                if key == "security_groups":
                    sg = []
                    for key_sg in args["security_groups"]:
                        tmp_sg = {}
                        tmp_sg["id"] = key_sg
                        sg.append(tmp_sg)
                    payload["security_groups"] = sg
                elif key == "subnet":
                    payload["subnet"] = {"id": subnet_info["id"]}
                else:
                    payload[key] = value

        try:
            path = ("/v1/instances/{}/network_interfaces?version={}"
                    "&generation={}".format(instance_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating instance interface. {}".format(error))
            raise
Beispiel #29
0
    def attach_volume(self, **kwargs):
        """Attach a volume to an instance

        :param instance: The instance name or ID
        :type instance: str
        :param volume: The identity of the volume to attach to the instance
        :type volume: str
        :param delete_volume_on_instance_delete: If set to true, when deleting
            the instance the volume will also be deleted
        :type delete_volume_on_instance_delete: bool, optional
        :param name: The user-defined name for this volume attachment
        :type name: str
        """
        args = ["instance", "volume"]
        check_args(args, **kwargs)

        args = {
            'instance':
            kwargs.get('instance'),
            'volume':
            kwargs.get('volume'),
            'delete_volume_on_instance_delete':
            kwargs.get('delete_volume_on_instance_delete'),
            'name':
            kwargs.get('name'),
        }

        instance_info = self.get_instance(args["instance"])
        if "errors" in instance_info:
            return instance_info

        volume_info = self.volume.get_volume(args["volume"])
        if "errors" in volume_info:
            return volume_info

        payload = {}
        for key, value in args.items():
            if key != "instance" and value is not None:
                if key == "volume":
                    payload["volume"] = {"id": volume_info["id"]}
                else:
                    payload[key] = value

        try:
            path = ("/v1/instances/{}/volume_attachments?version={}"
                    "&generation={}".format(instance_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating volume attachment. {}".format(error))
            raise
    def create_zone(self, **kwargs):
        """Create a zone in a specified resource instance

        :param dns_zone: The user-defined name to create
        :type dns_zone: str
        :param description: A description for the domain
        :type description: str, optional
        :param label: A label for the domain
        :type label: str, optional
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'name': kwargs.get('dns_zone'),
            'description': kwargs.get('description') or "",
            'label': kwargs.get('label') or "",
        }

        # get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            kwargs.get('resource_instance'))
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        zone = self.get_dns_zone(dns_zone=args['name'],
                                 resource_instance=resource_instance_guid)

        if "errors" in zone:
            for key_zone in zone["errors"]:
                if key_zone["code"] == "not_found":
                    payload = {}

                    # Construct payload
                    for key, value in args.items():
                        payload[key] = value

                    try:
                        # Connect to api endpoint for dns zone
                        path = ("/v1/instances/{}/dnszones"
                                ).format(resource_instance_guid)
                        # Return data
                        return qw("dns", "POST", path, headers(),
                                  json.dumps(payload))["data"]

                    except Exception as error:
                        print("Error creating dns zone. {}".format(error))
                        raise
        return zone