def __init__(self):
     print("--------constructor---------")
     logfile = '/tmp/vnf-ha-cloud-failover-func/fail_over.log'
     logging.basicConfig(filename=logfile, format='%(asctime)s:%(levelname)s:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
     loghandler = logging.handlers.TimedRotatingFileHandler(logfile,when="midnight")
     self.logger = logging.getLogger(__name__)
     self.logger.addHandler(loghandler)
     if self.apikey is None:
         self.parse_config_json()
     authenticator = IAMAuthenticator(self.apikey)
     self.service = VpcV1(authenticator=authenticator)
     self.service.set_service_url(self.vpc_url)
     self.service = VpcV1(self.version, authenticator=authenticator) 
     self.logger.info("Initialized vpc service")
Exemplo n.º 2
0
def detach_volume_from_worker(configuration: Configuration, cluster_id: str,
                              volume_id: str, worker_id: str):
    """
    detach_volume_from_worker: attach volume to worker nodes
    attr cluster_id str: Cluster ID 
    attr volume_id str: VolumeID
    attr worker_id str: Worker node ID
    """

    # Retrieve API Key from Configuration and create authenticator Object
    api_key = configuration.get("api_key")
    authenticator = IAMAuthenticator(api_key)

    # Create vpcV1 Api Service to retrieve the volumeattachementID needed by delete attachement method
    service = VpcV1('2020-06-02',
                    authenticator=authenticator,
                    generation=int(2))
    url = configuration.get("service_url",
                            'https://dallas.iaas.cloud.ibm.com/v1')
    service.service_url = url
    volume = service.get_volume(volume_id)._to_dict()
    if (volume['result']['volume_attachments'][0] is None):
        raise ValueError('This disk is not attached to any worker nodes')
    volume_attachment = volume['result']['volume_attachments'][0]['id']

    # Create Delete Attachement Model
    deleteAttachement = DeleteAttachementModel(
        cluster=cluster_id,
        volumeID=volume_id,
        volumeAttachmentID=volume_attachment,
        worker=worker_id)

    # Instatiate ContaierService to connect containers API
    service = ContainerService(authenticator)
    service.delete_raw_block_storage(deleteAttachement)
Exemplo n.º 3
0
    def __init__(self, ibm_vpc_config, mode):
        logger.debug("Creating IBM VPC client")
        self.name = 'ibm_vpc'
        self.config = ibm_vpc_config
        self.mode = mode

        self.endpoint = self.config['endpoint']
        self.region = self.endpoint.split('//')[1].split('.')[0]
        self.vpc_name = self.config.get('vpc_name')

        self.master = None
        self.workers = []

        iam_api_key = self.config.get('iam_api_key')
        self.custom_image = self.config.get('custom_lithops_image')

        authenticator = IAMAuthenticator(iam_api_key)
        self.ibm_vpc_client = VpcV1('2021-01-19', authenticator=authenticator)
        self.ibm_vpc_client.set_service_url(self.config['endpoint'] + '/v1')

        user_agent_string = 'ibm_vpc_{}'.format(self.config['user_agent'])
        self.ibm_vpc_client._set_user_agent_header(user_agent_string)

        msg = COMPUTE_CLI_MSG.format('IBM VPC')
        logger.info("{} - Region: {}".format(msg, self.region))
Exemplo n.º 4
0
    def __init__(self, ibm_vpc_config, mode):
        logger.debug("Creating IBM VPC client")
        self.name = 'ibm_vpc'
        self.config = ibm_vpc_config
        self.mode = mode

        self.endpoint = self.config['endpoint']
        self.region = self.endpoint.split('//')[1].split('.')[0]
        self.vpc_name = self.config.get('vpc_name')
        self.cache_dir = os.path.join(CACHE_DIR, self.name)

        logger.debug('Setting VPC endpoint to: {}'.format(self.endpoint))

        self.master = None
        self.workers = []

        iam_api_key = self.config.get('iam_api_key')
        self.custom_image = self.config.get('custom_lithops_image')

        authenticator = IAMAuthenticator(iam_api_key)
        self.ibm_vpc_client = VpcV1(VPC_API_VERSION,
                                    authenticator=authenticator)
        self.ibm_vpc_client.set_service_url(self.config['endpoint'] + '/v1')

        user_agent_string = 'ibm_vpc_{}'.format(self.config['user_agent'])
        self.ibm_vpc_client._set_user_agent_header(user_agent_string)

        # decorate instance public methods with except/retry logic
        decorate_instance(self.ibm_vpc_client, vpc_retry_on_except)

        msg = COMPUTE_CLI_MSG.format('IBM VPC')
        logger.info("{} - Region: {}".format(msg, self.region))
Exemplo n.º 5
0
    def parse(self, inventory, loader, path, cache=True):

        self.loader = loader
        self.inventory = inventory
        self.set_options()

        ibmcloud_api_key = os.environ.get('IBMCLOUD_API_KEY')
        if ibmcloud_api_key is None:
            display.debug("Please set environment variable IBMCLOUD_API_KEY")
            display.debug("Instructions for getting an API Key are here:")
            display.debug(
                "https://cloud.ibm.com/docs/iam?topic=iam-userapikey#create_user_key"
            )
            raise AnsibleError('Error getting IBM Cloud credentials')

        try:
            authenticator = IAMAuthenticator(ibmcloud_api_key)
            client = VpcV1('2019-09-24', authenticator=authenticator)
            instances = client.list_instances()
        except Exception as e:
            raise AnsibleError('Error in connecting to IBM Cloud: %s' %
                               to_native(e))

        #parse data and create inventory objects:
        for ins in instances.result['instances']:
            name = ins['name']
            vpc_name = ins['vpc']['name']
            ipv4 = ins['primary_network_interface']['primary_ipv4_address']
            display.debug("found host: %s %s %s" % (name, vpc_name, ipv4))
            self.inventory.add_host(name)
            self.inventory.set_variable(name, 'ansible_host', ipv4)
            self.inventory.set_variable(name, 'vpc_name', vpc_name)
Exemplo n.º 6
0
def create_ibmcloud_api_client(configuration: Configuration) -> VpcV1:
    api_key = configuration.get("api_key")
    gen = configuration.get("generation", 2)
    url = configuration.get("service_url", 'https://api.au-syd.databases.cloud.ibm.com/v5/ibm/')
    authenticator = IAMAuthenticator(api_key)
    service = VpcV1('2020-06-02', authenticator=authenticator, generation=int(gen))
    service.service_url = url
    return service
Exemplo n.º 7
0
def tag_virtual_instance(instance_id: str, configuration: Configuration, service: VpcV1, tagname: str):
    ins = service.get_instance(id=instance_id)._to_dict()
    crn = (ins['result']['crn'])
    resource = {'resource_id': crn}
    resources = [resource]
    api_key = configuration.get("api_key")
    authenticator = IAMAuthenticator(api_key)
    global_tagging = GlobalTaggingV1(authenticator=authenticator)
    global_tagging.attach_tag(resources=resources, tag_names=['chaostoolkit', tagname])
Exemplo n.º 8
0
    def _create_vpc_client(self):
        """
        Creates an IBM VPC python-sdk instance
        """
        authenticator = IAMAuthenticator(self.iam_api_key)
        ibm_vpc_client = VpcV1('2021-01-19', authenticator=authenticator)
        ibm_vpc_client.set_service_url(self.config['endpoint'] + '/v1')

        return ibm_vpc_client
Exemplo n.º 9
0
def tag_lb(lb_id: str, service: VpcV1, configuration: Configuration, *args):
    lb_ins = service.get_load_balancer(lb_id)._to_dict()
    crn = lb_ins['result']['crn']
    resource = {'resource_id': crn}
    resources = [resource]
    api_key = configuration.get("api_key")
    authenticator = IAMAuthenticator(api_key)
    global_tagging = GlobalTaggingV1(authenticator=authenticator)
    arr = ['chaostoolkit']
    arr.append(*args)
    global_tagging.attach_tag(resources=resources, tag_names=arr)
Exemplo n.º 10
0
    def _create_vpc_client(self):
        """
        Creates an IBM VPC python-sdk instance
        """
        authenticator = IAMAuthenticator(self.iam_api_key)
        ibm_vpc_client = VpcV1(VPC_API_VERSION, authenticator=authenticator)
        ibm_vpc_client.set_service_url(self.config['endpoint'] + '/v1')

        # decorate instance public methods with except/retry logic
        decorate_instance(self.ibm_vpc_client, vpc_retry_on_except)

        return ibm_vpc_client
Exemplo n.º 11
0
def get_ibm_service(access_key: str, service_url: str):
    """
    Return the authenticated connection from the given service_url.

    Args:
        access_key (str):   The access key(API key) of the user.
        service_url (str):  VPC endpoint to be used for provisioning.
    """
    authenticator = IAMAuthenticator(access_key)

    service = VpcV1(authenticator=authenticator)
    service.set_service_url(service_url=service_url)

    return service
def run_module():

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=False)

    # New resource required arguments checks
    missing_args = []
    for arg, _ in REQUIRED_PARAMETERS:
        if module.params[arg] is None:
            missing_args.append(arg)
    if missing_args:
        module.fail_json(msg=("missing required arguments: " +
                              ", ".join(missing_args)))

    # authenticate using api-key
    if module.params["ibmcloud_api_key"]:
        authenticator = IAMAuthenticator(module.params["ibmcloud_api_key"])
    elif module.params["bearer_token"]:
        authenticator = BearerTokenAuthenticator(module.params["bearer_token"])
    else:
        authenticator = BearerTokenAuthenticator(
            module.params["env_bearer_token"])

    service = VpcV1('2020-06-02', authenticator=authenticator)

    # Stop Instance
    #print("Stop Instance")
    try:
        stopIns = service.create_instance_action(
            instance_id=module.params["instance_id"],
            type=module.params["action_type"])
    except ApiException as e:
        module.fail_json(msg=("Failed to get expected response"))
        print("stop instances failed with status code " + str(e.code) + ": " +
              e.message)

    #print(stopIns)

    if stopIns.get_status_code() != 201:
        module.fail_json(msg=("Failed to get expected response"))
    module.exit_json(**stopIns.get_result())
# this program lists VPC services that you already have

from ibm_vpc import VpcV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_cloud_sdk_core import ApiException

authenticator = IAMAuthenticator("<<your-api-key>>")
service = VpcV1('2020-06-02', authenticator=authenticator)

service.set_service_url('https://eu-gb.iaas.cloud.ibm.com/v1')

#  Listing VPCs
print("List VPCs")
try:
    vpcs = service.list_vpcs().get_result()['vpcs']
except ApiException as e:
  print("List VPC failed with status code " + str(e.code) + ": " + e.message)
for vpc in vpcs:
    print(vpc['id'], "\t",  vpc['name'])

#  Listing Subnets
print("List Subnets")
try:
    subnets = service.list_subnets().get_result()['subnets']
except ApiException as e:
  print("List subnets failed with status code " + str(e.code) + ": " + e.message)
for subnet in subnets:
    print(subnet['id'], "\t",  subnet['name'])

#  Listing Instances
print("List Instances")
Exemplo n.º 14
0
def helper(params):
    authenticator = IAMAuthenticator(params["IAM_API_KEY"])
    global service
    service = VpcV1('2020-06-02', authenticator=authenticator)
    response = get_instance_id(params)
    return response
from ibm_vpc import VpcV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

apikey = '<apikey>'
authenticator = IAMAuthenticator(apikey)
service = VpcV1(authenticator=authenticator)
vpc_url = 'https://us-south.iaas.cloud.ibm.com'
service.set_service_url(vpc_url)
service = VpcV1('2020-04-10', authenticator=authenticator)

<codetoreplace>
print(response)
Exemplo n.º 16
0
  pp.pprint(sys.argv)
  print("-- end")

# debug_print()

APIKEY=os.getenv("APIKEY")
REGION=os.getenv("REGION")
VPN_GATEWAY_ID=os.getenv("VPN_GATEWAY_ID")
VPC_ID=os.getenv("VPC_ID")
ROUTING_TABLE_ID=os.getenv("ROUTING_TABLE_ID")
ZONE=os.getenv("ZONE")
ENTERPRISE_CIDR=os.getenv("ENTERPRISE_CIDR")
ROUTE_NAME=os.getenv("ROUTE_NAME")

authenticator = IAMAuthenticator(APIKEY)
service = VpcV1(authenticator=authenticator)
service_url = f"https://{REGION}.iaas.cloud.ibm.com/v1"
service.set_service_url(service_url)

def vpn_member(vpn_gateway_id, role):
  response = service.get_vpn_gateway(vpn_gateway_id)
  for member in response.result["members"]:
    if member["role"] == role:
      return member
  return None

def vpn_active_available_private_ip(vpn_gateway_id):
  member = vpn_member(vpn_gateway_id, "active")
  if member and member["status"] == "available":
    return member["private_ip"]["address"]
  return None
Exemplo n.º 17
0
def run_module():

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=False)

    # New resource required arguments checks
    missing_args = []
    for arg, _ in REQUIRED_PARAMETERS:
        if module.params[arg] is None:
            missing_args.append(arg)
    if missing_args:
        module.fail_json(msg=("missing required arguments: " +
                              ", ".join(missing_args)))

    if not module.params["instance_ip"] and not module.params["instance_id"]:
        module.fail_json(msg=(
            "missing required arguments: pass instance_ip or instance_id"))

    # authenticate using api-key
    if module.params["ibmcloud_api_key"]:
        authenticator = IAMAuthenticator(module.params["ibmcloud_api_key"])
    elif module.params["bearer_token"]:
        authenticator = BearerTokenAuthenticator(module.params["bearer_token"])
    else:
        authenticator = BearerTokenAuthenticator(
            module.params["env_bearer_token"])

    service = VpcV1('2020-06-02', authenticator=authenticator)

    instanceId = module.params["instance_id"]
    if module.params["instance_ip"]:
        try:
            floatingIps = service.list_floating_ips().get_result(
            )['floating_ips']
            instances = service.list_instances().get_result()['instances']
        except ApiException as e:
            print("List instances/floatingIp failed with status code " +
                  str(e.code) + ": " + e.message)
        target = ""
        for floatingIp in floatingIps:
            if floatingIp["address"] == module.params["instance_ip"]:
                target = floatingIp["target"]["id"]
        for instance in instances:
            if target == "":
                if instance["primary_network_interface"][
                        "primary_ipv4_address"] == module.params[
                            "instance_ip"]:
                    instanceId = instance["id"]
                    # print(instance['id'], "\t",  instance['name'])
            elif instance["primary_network_interface"]["id"] == target:
                instanceId = instance["id"]
                # print(instance['id'], "\t",  instance['name'])
        if instanceId == "":
            module.fail_json(msg=("instance not found"))

    try:
        stopIns = service.create_instance_action(
            instance_id=instanceId, type=module.params["action_type"])
    except ApiException as e:
        module.fail_json(msg=("Failed to get expected response"))
        print("stop instances failed with status code " + str(e.code) + ": " +
              e.message)

    #print(stopIns)

    if stopIns.get_status_code() != 201:
        module.fail_json(msg=("Failed to get expected response"))
    module.exit_json(**stopIns.get_result())