Exemple #1
0
def main():
    module = AnsibleModule(argument_spec=dict(
        auth_token=dict(default=os.environ.get(PACKET_API_TOKEN_ENV_VAR),
                        no_log=True),
        count=dict(type='int', default=1),
        count_offset=dict(type='int', default=1),
        device_ids=dict(type='list'),
        facility=dict(default='ewr1'),
        features=dict(type='dict'),
        hostnames=dict(type='list', aliases=['name']),
        locked=dict(type='bool', default=False),
        operating_system=dict(),
        plan=dict(),
        project_id=dict(required=True),
        state=dict(choices=ALLOWED_STATES, default='present'),
        user_data=dict(default=None),
        wait=dict(type='bool', default=False),
        wait_timeout=dict(type='int', default=60),
    ),
                           required_one_of=[(
                               'device_ids',
                               'hostnames',
                           )],
                           mutually_exclusive=[
                               ('hostnames', 'device_ids'),
                               ('count', 'device_ids'),
                               ('count_offset', 'device_ids'),
                           ])

    if not HAS_PACKET_SDK:
        module.fail_json(msg='packet required for this module')

    if not module.params.get('auth_token'):
        _fail_msg = ("if Packet API token is not in environment variable %s, "
                     "the auth_token parameter is required" %
                     PACKET_API_TOKEN_ENV_VAR)
        module.fail_json(msg=_fail_msg)

    auth_token = module.params.get('auth_token')

    packet_conn = packet.Manager(auth_token=auth_token)

    state = module.params.get('state')

    try:
        module.exit_json(**act_on_devices(state, module, packet_conn))
    except Exception as e:
        module.fail_json(msg='failed to set machine state %s, error: %s' %
                         (state, str(e)))
Exemple #2
0
    def client(self):
        """If client not set, a new client is created

        :raises RuntimeError: Auth token not configured
        :return: client
        :rtype:
        """

        if not self._client:
            if not self.auth_token_:
                raise j.exceptions.Base(
                    "please configure your auth_token, do: 'js_config configure -l j.clients.packetnet -i {}'"
                    .format(self.name))
            self._client = packet.Manager(auth_token=self.auth_token_)
        return self._client
Exemple #3
0
def packet_remove_devices(device_names):
    manager = packet.Manager(auth_token=common.packet_rancher_auth_token)
    devices = manager.list_devices(project_id=common.packet_rancher_project_id)
    for each in devices:
        if each.hostname not in device_names:
            continue
        retries = 5
        while retries >= 0:
            retries -= 1
            try:
                each.delete()
                break
            except:
                time.sleep(30)
                continue
Exemple #4
0
def main():
    module = AnsibleModule(argument_spec=dict(
        state=dict(choices=['present', 'absent'], default='present'),
        auth_token=dict(type='str',
                        fallback=(env_fallback, [PACKET_API_TOKEN_ENV_VAR]),
                        no_log=True),
        name=dict(type='str'),
        id=dict(type='str'),
        org_id=dict(type='str'),
        payment_method=dict(type='str'),
        custom_data=dict(type='str'),
    ),
                           supports_check_mode=True,
                           required_one_of=[(
                               "name",
                               "id",
                           )],
                           mutually_exclusive=[
                               ('name', 'id'),
                           ])
    if not HAS_PACKET_SDK:
        module.fail_json(msg='packet required for this module')

    if not module.params.get('auth_token'):
        _fail_msg = ("if Packet API token is not in environment variable {0}, "
                     "the auth_token parameter is required".format(
                         PACKET_API_TOKEN_ENV_VAR))
        module.fail_json(msg=_fail_msg)

    auth_token = module.params.get('auth_token')

    packet_conn = packet.Manager(auth_token=auth_token)

    state = module.params.get('state')

    if state in ['present', 'absent']:
        if module.check_mode:
            module.exit_json(changed=False)

        try:
            module.exit_json(**act_on_project(state, module, packet_conn))
        except Exception as e:
            module.fail_json(msg="failed to set project state {0}: {1}".format(
                state, to_native(e)))
    else:
        module.fail_json(
            msg="{0} is not a valid state for this module".format(state))
Exemple #5
0
def packet_auth(auth_token, project_id):
    pattern = re.compile("([A-z0-9-])")
    print(not project_id)
    print(not auth_token)
    if not auth_token or not project_id or not pattern.match(
            auth_token) or not pattern.match(project_id):
        return False
    manager = packet.Manager(auth_token=auth_token)
    try:
        projects = manager.list_projects()
        for project in projects:
            if project.id == project_id:
                return True
    except packet.baseapi.Error:
        return False

    return False
Exemple #6
0
def packet_create_register_host(name, registration_command):
    manager = packet.Manager(auth_token=common.packet_rancher_auth_token)
    log.info("creating packet instance name: %s", name)
    device = manager.create_device(project_id=common.packet_rancher_project_id,
                                   hostname=name,
                                   plan=packet_host_machine_type,
                                   facility='ewr1',
                                   operating_system=packet_host_os_img,
                                   userdata=packet_host_cloud_config)

    # wait for initializing and reboot
    device = packet_wait_for_creation(manager, device)
    log.info("Packet device name: %s created, registering it to cattle ...",
             device.hostname)
    packet_register_to_cattle(device, registration_command)

    return device
Exemple #7
0
def _wait_for_status(status_type, object_id, status=None, timeout=500, quiet=True):
    '''
    Wait for a certain status from Packet.
    status_type
        device or volume
    object_id
        The ID of the Packet device or volume to wait on. Required.
    status
        The status to wait for.
    timeout
        The amount of time to wait for a status to update.
    quiet
        Log status updates to debug logs when False. Otherwise, logs to info.
    '''
    if status is None:
        status = "ok"

    interval = 5
    iterations = int(timeout / interval)

    vm_ = get_configured_provider()
    manager = packet.Manager(auth_token=vm_['token'])

    for i in range(0, iterations):
        get_object = getattr(manager, "get_{status_type}".format(status_type=status_type))
        obj = get_object(object_id)

        if obj.state == status:
            return obj

        time.sleep(interval)
        if quiet:
            log.info('Status for Packet {0} is \'{1}\', waiting for \'{2}\'.'.format(
                object_id,
                obj.state,
                status)
            )
        else:
            log.debug('Status for Packet {0} is \'{1}\', waiting for \'{2}\'.'.format(
                object_id,
                obj.state,
                status)
            )

    return obj
Exemple #8
0
def _wait_for_status(status_type,
                     object_id,
                     status=None,
                     timeout=500,
                     quiet=True):
    """
    Wait for a certain status from Packet.
    status_type
        device or volume
    object_id
        The ID of the Packet device or volume to wait on. Required.
    status
        The status to wait for.
    timeout
        The amount of time to wait for a status to update.
    quiet
        Log status updates to debug logs when False. Otherwise, logs to info.
    """
    if status is None:
        status = "ok"

    interval = 5
    iterations = int(timeout / interval)

    vm_ = get_configured_provider()
    manager = packet.Manager(auth_token=vm_["token"])

    for i in range(0, iterations):
        get_object = getattr(
            manager, "get_{status_type}".format(status_type=status_type))
        obj = get_object(object_id)

        if obj.state == status:
            return obj

        time.sleep(interval)
        log.log(
            logging.INFO if not quiet else logging.DEBUG,
            "Status for Packet %s is '%s', waiting for '%s'.",
            object_id,
            obj.state,
            status,
        )

    return obj
def main():
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(choices=STATES, default="present"),
            auth_token=dict(type='str',
                            fallback=(env_fallback, [PACKET_API_TOKEN_ENV_VAR
                                                     ]),
                            no_log=True),
            volume=dict(type="str", required=True),
            project_id=dict(type="str", required=True),
            device=dict(type="str"),
        ),
        supports_check_mode=True,
    )

    if not HAS_PACKET_SDK:
        module.fail_json(msg='packet required for this module')

    if not module.params.get('auth_token'):
        _fail_msg = ("if Packet API token is not in environment variable {0}, "
                     "the auth_token parameter is required".format(
                         PACKET_API_TOKEN_ENV_VAR))
        module.fail_json(msg=_fail_msg)

    auth_token = module.params.get('auth_token')

    packet_conn = packet.Manager(auth_token=auth_token)

    state = module.params.get('state')

    if state in STATES:
        if module.check_mode:
            module.exit_json(changed=False)

        try:
            module.exit_json(
                **act_on_volume_attachment(state, module, packet_conn))
        except Exception as e:
            module.fail_json(
                msg="failed to set volume_attachment state {0}: {1}".format(
                    state, to_native(e)))
    else:
        module.fail_json(
            msg="{0} is not a valid state for this module".format(state))
def main():
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(choices=['present', 'absent'], default='present'),
            auth_token=dict(default=os.environ.get(PACKET_API_TOKEN_ENV_VAR),
                            no_log=True),
            label=dict(type='str', aliases=['name'], default=None),
            id=dict(type='str', default=None),
            fingerprint=dict(type='str', default=None),
            key=dict(type='str', default=None, no_log=True),
            key_file=dict(type='path', default=None),
        ),
        mutually_exclusive=[
            ('label', 'id'),
            ('label', 'fingerprint'),
            ('id', 'fingerprint'),
            ('key', 'fingerprint'),
            ('key', 'id'),
            ('key_file', 'key'),
        ]
    )

    if not HAS_PACKET_SDK:
        module.fail_json(msg='packet required for this module')

    if not module.params.get('auth_token'):
        _fail_msg = ("if Packet API token is not in environment variable %s, "
                     "the auth_token parameter is required" %
                     PACKET_API_TOKEN_ENV_VAR)
        module.fail_json(msg=_fail_msg)

    auth_token = module.params.get('auth_token')

    packet_conn = packet.Manager(auth_token=auth_token)

    state = module.params.get('state')

    if state in ['present', 'absent']:
        try:
            module.exit_json(**act_on_sshkeys(state, module, packet_conn))
        except Exception as e:
            module.fail_json(msg='failed to set sshkey state: %s' % str(e))
    else:
        module.fail_json(msg='%s is not a valid state for this module' % state)
Exemple #11
0
def authenticate(args):
    headers = {
        "Accept": "application/json",
        "X-Auth-Token": args.api_key,
        "X-Consumer-Token": args.consumer_token,
        "X-Packet-Staff": "true"
    }
    try:
        _, response = do_request("GET", "api.packet.net", "/staff/labels", headers, "")
        if response.status != 200 and response.status != 201:
            print("ERROR: Could not validate Auth Token.")
            sys.exit(1)
        else:
            manager = packet.Manager(auth_token=args.api_key)
    except:
        print("ERROR: Could not validate Auth Token.")
        sys.exit(1)

    return manager
Exemple #12
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            auth_token=dict(
                type='str',
                fallback=(env_fallback, [PACKET_API_TOKEN_ENV_VAR]),
                no_log=True
            ),
            device_id=dict(type='str'),
            hostname=dict(type='str'),
            project_id=dict(type='str'),
            device_count=dict(type='int', default=PROJECT_MAX_DEVICES),
            cidr=dict(type='str', required=True, aliases=['name']),
            state=dict(choices=ALLOWED_STATES, default='present'),
        ),
        supports_check_mode=True,
        mutually_exclusive=[('hostname', 'device_id')],
        required_one_of=[['hostname', 'device_id', 'project_id']],
        required_by=dict(
            hostname=('project_id',),
        ),
    )

    if not HAS_PACKET_SDK:
        module.fail_json(msg='packet required for this module')

    if not module.params.get('auth_token'):
        _fail_msg = ("if Packet API token is not in environment variable {0}, "
                     "the auth_token parameter is required".format(PACKET_API_TOKEN_ENV_VAR))
        module.fail_json(msg=_fail_msg)

    auth_token = module.params.get('auth_token')

    packet_conn = packet.Manager(auth_token=auth_token)

    state = module.params.get('state')

    try:
        module.exit_json(**act_on_assignment(state, module, packet_conn))
    except Exception as e:
        module.fail_json(
            msg="failed to set IP subnet to state {0}, error: {1}".format(state, to_native(e)))
def main(config):
    rows = []
    manager = packet.Manager(auth_token=config['token'])
    found = 0
    for device in get_devices(manager):
        found += 1
        debug("# {} ({})".format(device['hostname'], device['address']))
        if device['type'] not in config['plans']:
            debug(
                "# Skipping {} (type {}) as it has no configured plan".format(
                    device['hostname'], device['type']))
            continue

        default_stats = config['plans'][device['type']]
        if device['hostname'] in config['name_overrides']:
            specific_stats = config['name_overrides'][device['hostname']]
        else:
            specific_stats = {}

        lookup = lambda key: specific_stats.get(
            key, device.get(key, default_stats.get(key)))
        lookup_default = lambda key, default: default if not lookup(
            key) else lookup(key)

        # root@address system,list /var/lib/ssh.key maxJobs speedFactor feature,list mandatory,features public-host-key
        rows.append(" ".join([
            "{user}@{host}".format(user=lookup("user"),
                                   host=lookup("address")),
            ",".join(lookup("system_types")),
            str(lookup("ssh_key")),
            str(lookup("max_jobs")),
            str(lookup("speed_factor")),
            ",".join(lookup_default("features", ["-"])),
            ",".join(lookup_default("mandatory_features", ["-"])),
            base64.b64encode(device['host_key'].encode()).decode("utf-8")
        ]))

    debug("# {} / {}".format(len(rows), found))
    print("\n".join(rows))
Exemple #14
0
    def launch(self, node):
        label = self.pool.labels[node.type[0]]

        manager = packet.Manager(self.provider.auth_token)

        try:
            device = manager.create_device(
                project_id=self.provider.project_id,
                hostname=node.id,
                plan=label.plan,
                facility=self.provider.facility,
                operating_system=label.operating_system)
        except packet.baseapi.Error as e:
            self.log.info("Node id %s failed %s", e.args[0])
            node.state = zk.FAILED
            self.zk.storeNode(node)
            return

        node.external_id = device.id
        node.state = zk.READY
        self.zk.storeNode(node)
        self.log.info("Node id %s is ready", node.id)
Exemple #15
0
    def __init__(self, **kwargs):
        local_settings = {}
        for key in AnsibleMetalModule.default_settings:
            try:
                local_settings[key] = kwargs.pop(key)
            except KeyError:
                local_settings[key] = AnsibleMetalModule.default_settings[key]
        self.settings = local_settings

        if local_settings["default_args"]:
            argument_spec_full = metal_argument_spec()
            try:
                argument_spec_full.update(kwargs["argument_spec"])
            except (TypeError, NameError):
                pass
            kwargs["argument_spec"] = argument_spec_full

        if local_settings["project_id_arg"]:
            argument_spec_full = metal_project_id_argument_spec(
                local_settings["project_id_required"])
            try:
                argument_spec_full.update(kwargs["argument_spec"])
            except (TypeError, NameError):
                pass
            kwargs["argument_spec"] = argument_spec_full

        self._module = AnsibleMetalModule.default_settings["module_class"](
            **kwargs)

        self.check_mode = self._module.check_mode
        self._diff = self._module._diff
        self._name = self._module._name

        if not HAS_METAL_SDK:
            self.fail_json(msg='python-packet required for this module')

        if local_settings["default_args"]:
            self.metal_conn = packet.Manager(
                auth_token=self.params.get('api_token'))
Exemple #16
0
    def setUpClass(self):
        self.manager = packet.Manager(auth_token=os.environ["PACKET_AUTH_TOKEN"])
        org_id = self.manager.list_organizations()[0].id
        self.project = self.manager.create_organization_project(
            org_id=org_id,
            name="Int-Tests-Device_{}".format(
                datetime.utcnow().strftime("%Y%m%dT%H%M%S.%f")[:-3]
            ),
        )

        self.manager.enable_project_bgp_config(
            project_id=self.project.id, deployment_type="local", asn=65000
        )

        self.device = self.manager.create_device(
            self.project.id, "devicetest", "baremetal_0", "ewr1", "centos_7"
        )

        while True:
            if self.manager.get_device(self.device.id).state == "active":
                break
            time.sleep(2)
Exemple #17
0
def main():
    print("instantiating manager")
    m = packet.Manager(token)
    print("instantiating device")
    d = Device(m)
    print("creating device")
    d.create(project, hostname, plan, facility, ipxe_script_url)
    start = time.time()
    print(d)

    state = None
    while True:
        state, oldstate = d.state(), state
        if state != oldstate:
            print(d)
        if state == "active":
            break
        time.sleep(30)

    d.wait_for_ssh()
    print(d, "time-to-active", time.time() - start)
    print(d, "deleting")
    d.delete()
    print(d, "test-time", time.time() - start)
Exemple #18
0
def avail_projects(call=None):
    """
    Return available Packet projects.

    CLI Example:

    .. code-block:: bash

        salt-cloud -f avail_projects packet-provider
    """
    if call == "action":
        raise SaltCloudException(
            "The avail_projects function must be called with -f or --function."
        )

    vm_ = get_configured_provider()
    manager = packet.Manager(auth_token=vm_["token"])

    ret = {}

    for project in manager.list_projects():
        ret[project.name] = project.__dict__

    return ret
Exemple #19
0
 def _connect(self):
     ''' create connection to api server'''
     manager = packet.Manager(
         auth_token=self.api_token,
         consumer_token="ansible-equinix-metal-inventory")
     return manager
Exemple #20
0
#!/usr/bin/env python

from __future__ import print_function

import json
import os

import packet

m = packet.Manager(os.getenv("PACKET_API_TOKEN"))
c = m.get_capacity()
cap = {}

for fac in c:
    for plan, v in c[fac].items():
        p = cap.get(plan, {})
        level = v["level"]
        lvl = p.get(level, [])
        lvl.append(fac)
        p[level] = lvl
        cap[plan] = p

print(json.dumps(cap))
Exemple #21
0
def create(vm_):
    """
    Create a single Packet VM.
    """
    name = vm_["name"]

    if not is_profile_configured(vm_):
        return False

    __utils__["cloud.fire_event"](
        "event",
        "starting create",
        "salt/cloud/{}/creating".format(name),
        args=__utils__["cloud.filter_event"](
            "creating", vm_, ["name", "profile", "provider", "driver"]),
        sock_dir=__opts__["sock_dir"],
        transport=__opts__["transport"],
    )

    log.info("Creating Packet VM %s", name)

    manager = packet.Manager(auth_token=vm_["token"])

    __utils__["cloud.fire_event"](
        "event",
        "requesting instance",
        "salt/cloud/{}/requesting".format(vm_["name"]),
        args=__utils__["cloud.filter_event"](
            "requesting", vm_, ["name", "profile", "provider", "driver"]),
        sock_dir=__opts__["sock_dir"],
        transport=__opts__["transport"],
    )

    device = manager.create_device(
        project_id=vm_["project_id"],
        hostname=name,
        plan=vm_["size"],
        facility=vm_["location"],
        operating_system=vm_["image"],
    )

    device = _wait_for_status("device", device.id, status="active")

    if device.state != "active":
        log.error(
            "Error creating %s on PACKET\n\n"
            "while waiting for initial ready status",
            name,
            exc_info_on_loglevel=logging.DEBUG,
        )

    # Define which ssh_interface to use
    ssh_interface = _get_ssh_interface(vm_)

    # Pass the correct IP address to the bootstrap ssh_host key
    if ssh_interface == "private_ips":
        for ip in device.ip_addresses:
            if ip["public"] is False:
                vm_["ssh_host"] = ip["address"]
                break
    else:
        for ip in device.ip_addresses:
            if ip["public"] is True:
                vm_["ssh_host"] = ip["address"]
                break

    key_filename = config.get_cloud_config_value("private_key",
                                                 vm_,
                                                 __opts__,
                                                 search_global=False,
                                                 default=None)

    vm_["key_filename"] = key_filename

    vm_["private_key"] = key_filename

    # Bootstrap!
    ret = __utils__["cloud.bootstrap"](vm_, __opts__)

    ret.update({"device": device.__dict__})

    if vm_.get("storage_tier") and vm_.get("storage_size"):
        # create storage and attach it to device

        volume = manager.create_volume(
            vm_["project_id"],
            "{}_storage".format(name),
            vm_.get("storage_tier"),
            vm_.get("storage_size"),
            vm_.get("location"),
            snapshot_count=vm_.get("storage_snapshot_count", 0),
            snapshot_frequency=vm_.get("storage_snapshot_frequency"),
        )

        volume.attach(device.id)

        volume = _wait_for_status("volume", volume.id, status="active")

        if volume.state != "active":
            log.error(
                "Error creating %s on PACKET\n\n"
                "while waiting for initial ready status",
                name,
                exc_info_on_loglevel=logging.DEBUG,
            )

        ret.update({"volume": volume.__dict__})

    log.info("Created Cloud VM '%s'", name)

    log.debug("'%s' VM creation details:\n%s", name,
              pprint.pformat(device.__dict__))

    __utils__["cloud.fire_event"](
        "event",
        "created instance",
        "salt/cloud/{}/created".format(name),
        args=__utils__["cloud.filter_event"](
            "created", vm_, ["name", "profile", "provider", "driver"]),
        sock_dir=__opts__["sock_dir"],
        transport=__opts__["transport"],
    )

    return ret
Exemple #22
0
    def setUpClass(cls):
        cls.manager = packet.Manager(
            auth_token=os.environ["PACKET_AUTH_TOKEN"])

        cls.email = cls.manager.add_email("john.doe{}@packet.com".format(
            random.randint(1, 1001)))
Exemple #23
0
 def setUpClass(self):
     self.manager = packet.Manager(auth_token=os.environ["PACKET_AUTH_TOKEN"])
     orgs = self.manager.list_organizations()
     self.org_id = orgs[0].id
Exemple #24
0
                           os.environ.get("PACKETKEY"))
PROJECTID = os.environ.get(
    "PACKET_PROJECT_ID",
    os.environ.get("PACKET_PROJECT", os.environ.get("PROJECTID")))
if PACKETKEY is None:
    raise RuntimeError(
        "PACKET_API_AUTH_TOKEN or PACKETKEY(deprecated) env var not set")

if PROJECTID is None:
    raise RuntimeError(
        "PACKET_PROJECT_ID or PROJECTID(deprecated) env var not set")

RULESFILE = os.environ.get("RULESFILE", "/data/pktables.rules")
CHAIN = os.environ.get("CHAIN", "PKTABLES")

manager = packet.Manager(auth_token=PACKETKEY)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Update iptables from Packet Production Project.")
    parser.add_argument(
        "--dry-run",
        dest="dryrun",
        action="store_true",
        help=
        "do not apply the changes, only display the rules that will be applied",
    )
    args = parser.parse_args()

    networks = []
    data = manager.call_api("projects/%s/ips" % PROJECTID)
Exemple #25
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--project", help="project name")
    parser.add_argument("--host", help="host name")
    parser.add_argument("--vol", help="volume name")
    parser.add_argument("--listplans", help="list plans", action="store_true")
    parser.add_argument("--listprojects",
                        help="list projects",
                        action="store_true")
    parser.add_argument("--listhosts", help="list hosts", action="store_true")
    parser.add_argument("--listvols", help="list volumes", action="store_true")
    parser.add_argument("--createvol",
                        help="create volumes",
                        action="store_true")
    parser.add_argument("--createhost",
                        help="create new host",
                        action="store_true")
    parser.add_argument("--deletehost",
                        help="delete host",
                        action="store_true")
    parser.add_argument("--plan", help="plan when creating host")
    parser.add_argument("--facility", help="facility")
    parser.add_argument("--listkeys",
                        help="list ssh keys",
                        action="store_true")
    parser.add_argument("--listfacility",
                        help="list all facilities",
                        action="store_true")
    parser.add_argument("--listos",
                        help="list operating systems",
                        action="store_true")
    parser.add_argument("--os", help="operating systems")
    parser.add_argument("--key", help="ssh key label")
    parser.add_argument("--attach", help="attach volume", action="store_true")
    parser.add_argument("--detach", help="detach volume", action="store_true")

    args = parser.parse_args()

    with open("apikeys") as f:
        content = f.readlines()
    content = [x.strip() for x in content]
    apikey = content[0]

    manager = packet.Manager(auth_token=apikey)

    projects = manager.list_projects()

    if args.listprojects:
        for project in projects:
            print(project.name)

    assert (len(projects) > 0)

    proj = None

    if args.project:
        for project in projects:
            if project.name == args.project:
                proj = project

    if args.listplans:
        plans = manager.list_plans()
        for plan in plans:
            print(plan)

    params = {'per_page': 50}

    if not proj:
        return

    devices = manager.list_devices(project_id=proj.id, params=params)
    host = None
    for device in devices:
        if device.hostname == args.host:
            host = device
        if args.listhosts:
            print("%s %s %s %s" %
                  (device.hostname, device.ip_addresses[0]["address"],
                   device.ip_addresses[2]["address"], device.state))

    vols = manager.list_volumes(project_id=proj.id)
    volume = None
    for vol in vols:
        if vol.name == args.vol:
            volume = vol
        if args.listvols:
            print("%s %dGB %s" % (vol.name, vol.size, vol.state))

    facilities = manager.list_facilities()
    for facility in facilities:
        if args.listfacility:
            print(facility.code)

    if args.listkeys:
        keys = manager.list_ssh_keys()
        for key in keys:
            print(key.label)

    if args.listos:
        oses = manager.list_operating_systems()
        for os in oses:
            print(os.slug)

    if args.deletehost:
        assert (host != None)
        host.delete()

    if args.createhost:
        assert (args.host != None)
        assert (args.facility != None)
        assert (args.plan != None)
        assert (args.os != None)
        host = manager.create_device(project_id=proj.id,
                                     facility=args.facility,
                                     hostname=args.host,
                                     plan=args.plan,
                                     operating_system=args.os)
    if args.attach:
        assert (volume != None)
        assert (host != None)
        volume.attach(host.id)
    if args.detach:
        assert (volume != None)
        volume.detach()
Exemple #26
0
 def setUpClass(self):
     self.manager = packet.Manager(
         auth_token=os.environ["PACKET_AUTH_TOKEN"])
     self.manager.turn_on_vpn()
Exemple #27
0
def create(vm_):
    '''
    Create a single Packet VM.
    '''
    name = vm_['name']

    if not is_profile_configured(vm_):
        return False

    # Since using "provider: <provider-engine>" is deprecated, alias provider
    # to use driver: "driver: <provider-engine>"
    if 'provider' in vm_:
        vm_['driver'] = vm_.pop('provider')

    __utils__['cloud.fire_event']('event',
                                  'starting create',
                                  'salt/cloud/{0}/creating'.format(name),
                                  args={
                                      'name': name,
                                      'profile': vm_['profile'],
                                      'provider': vm_['driver'],
                                  },
                                  sock_dir=__opts__['sock_dir'],
                                  transport=__opts__['transport'])

    log.info('Creating Packet VM {0}'.format(name))

    manager = packet.Manager(auth_token=vm_['token'])

    device = manager.create_device(project_id=vm_['project_id'],
                                   hostname=name,
                                   plan=vm_['size'],
                                   facility=vm_['location'],
                                   operating_system=vm_['image'])

    device = _wait_for_status('device', device.id, status="active")

    if device.state != "active":
        log.error('Error creating {0} on PACKET\n\n'
                  'while waiting for initial ready status'.format(name),
                  exc_info_on_loglevel=logging.DEBUG)

    # Define which ssh_interface to use
    ssh_interface = _get_ssh_interface(vm_)

    # Pass the correct IP address to the bootstrap ssh_host key
    if ssh_interface == 'private_ips':
        for ip in device.ip_addresses:
            if ip['public'] is False:
                vm_['ssh_host'] = ip['address']
                break
    else:
        for ip in device.ip_addresses:
            if ip['public'] is True:
                vm_['ssh_host'] = ip['address']
                break

    key_filename = config.get_cloud_config_value('private_key',
                                                 vm_,
                                                 __opts__,
                                                 search_global=False,
                                                 default=None)

    vm_['key_filename'] = key_filename

    vm_['private_key'] = key_filename

    # Bootstrap!
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update({'device': device.__dict__})

    if vm_.get('storage_tier') and vm_.get('storage_size'):
        # create storage and attach it to device

        volume = manager.create_volume(
            vm_['project_id'],
            "{0}_storage".format(name),
            vm_.get('storage_tier'),
            vm_.get('storage_size'),
            vm_.get('location'),
            snapshot_count=vm_.get('storage_snapshot_count', 0),
            snapshot_frequency=vm_.get('storage_snapshot_frequency'))

        volume.attach(device.id)

        volume = _wait_for_status('volume', volume.id, status="active")

        if volume.state != "active":
            log.error('Error creating {0} on PACKET\n\n'
                      'while waiting for initial ready status'.format(name),
                      exc_info_on_loglevel=logging.DEBUG)

        ret.update({'volume': volume.__dict__})

    log.info('Created Cloud VM \'{0}\''.format(name))

    log.debug('\'{0}\' VM creation details:\n{1}'.format(
        name, pprint.pformat(device.__dict__)))

    __utils__['cloud.fire_event']('event',
                                  'created instance',
                                  'salt/cloud/{0}/created'.format(name),
                                  args={
                                      'name': name,
                                      'profile': vm_['profile'],
                                      'provider': vm_['driver'],
                                  },
                                  sock_dir=__opts__['sock_dir'],
                                  transport=__opts__['transport'])

    return ret
Exemple #28
0
def connect(api_token):
    return packet.Manager(auth_token=api_token)
Exemple #29
0
    print('Giving the machine time till it finish booting')
    time.sleep(150)

    print('preparing machine for tests')
    config = configparser.ConfigParser()
    config.read('config.ini')
    config['main']['target_ip'] = dev.ip_addresses[0]['address']
    config['main']['machine_hostname'] = hostname
    with open('config.ini', 'w') as configfile:
        config.write(configfile)


if __name__ == '__main__':
    action = sys.argv[1]
    token = sys.argv[2]
    manager = packet.Manager(auth_token=token)
    print(os.system('echo $TRAVIS_EVENT_TYPE'))
    if action == 'delete':
        print('deleting the g8os machine ..')
        delete_device(manager)
    else:
        branch = sys.argv[3]
        if len(sys.argv) == 5:
            branch = sys.argv[4]
        print('branch: {}'.format(branch))
        t = check_status(True, branch)
        if t != 'No_build_triggered':
            print('build has been started at {}'.format(t))
            print('waiting for g8os build to pass ..')
            check_status(False, branch)
            time.sleep(2)
import packet
import os

# Collect input variables from workflow
API_key = os.getenv("INPUT_API_KEY")
key_label = os.getenv("INPUT_KEY_LABEL")
public_key = os.getenv("INPUT_PUBLIC_KEY")

# Check if required inputs have been received
if API_key == "No key supplied" or public_key == "No key supplied":
    raise ValueError(
        f"Cannot supply empty value.\n Current API key is: %s\nCurrent public key is: %s"
        % (API_key, public_key))

# Create Packet.com API client
manager = packet.Manager(auth_token=API_key)

key = manager.create_ssh_key(label=key_label, public_key=public_key)

# Set outputs for action
print(f"::set-output name=key_id::{key.id}")
print(f"::set-output name=key_owner::{key.owner}")

# Profit