示例#1
0
def make_names_data(inventory_filename=None):
    show_warning()

    if not inventory_filename:
        raise InventoryError("No Ansible inventory filename provided!")

    if not path.exists(inventory_filename):
        raise InventoryError(("Could not find Ansible inventory file: {0}"
                              ).format(inventory_filename), )

    return parse_inventory(inventory_filename)
示例#2
0
def make_names_data(host_image_str):
    try:
        hostname, image = host_image_str.split(':', 1)
    except (AttributeError, ValueError):  # failure to parse the host_image_str
        raise InventoryError('No ssh host or docker base image provided!')

    if not image:
        raise InventoryError('No docker base image provided!')

    show_warning()

    yield ('@dockerssh/{0}:{1}'.format(hostname, image),
           {'ssh_hostname': hostname, 'docker_image': image},
           ['@dockerssh'])
示例#3
0
def parse_inventory(inventory_filename):
    # fallback to INI if no extension
    extension = inventory_filename.split(
        ".")[-1] if "." in inventory_filename else "ini"

    # host:set(groups) mapping
    host_to_groups = {}

    if extension in ["ini"]:
        host_to_groups = parse_inventory_ini(inventory_filename)
    elif extension in ["json"]:
        with open(inventory_filename) as inventory_file:
            inventory_tree = json.load(inventory_file)
            # close file early
        host_to_groups = parse_inventory_tree(inventory_tree)
    elif extension in ["yaml", "yml"]:
        if yaml is None:
            raise Exception(
                ("To parse YAML Ansible inventories requires `pyyaml`. "
                 "Install it with `pip install pyyaml`."), )
        with open(inventory_filename) as inventory_file:
            inventory_tree = yaml.safe_load(inventory_file)
            # close file early
        host_to_groups = parse_inventory_tree(inventory_tree)
    else:
        raise InventoryError(
            ("Ansible inventory file format not supported: {0}"
             ).format(extension))

    return [(host, {}, sorted(list(host_to_groups.get(host))))
            for host in host_to_groups]
示例#4
0
def parse_inventory(inventory_filename):
    # fallback to INI if no extension
    extension = inventory_filename.split(
        '.')[-1] if '.' in inventory_filename else 'ini'

    # host:set(groups) mapping
    host_to_groups = {}

    if extension in ['ini']:
        host_to_groups = parse_inventory_ini(inventory_filename)
    elif extension in ['json']:
        with open(inventory_filename) as inventory_file:
            inventory_tree = json.load(inventory_file)
            # close file early
        host_to_groups = parse_inventory_tree(inventory_tree)
    elif extension in ['yaml', 'yml']:
        if yaml is None:
            raise Exception(
                ('To parse YAML Ansible inventories requires `pyyaml`. '
                 'Install it with `pip install pyyaml`.'))
        with open(inventory_filename) as inventory_file:
            inventory_tree = yaml.safe_load(inventory_file)
            # close file early
        host_to_groups = parse_inventory_tree(inventory_tree)
    else:
        raise InventoryError(
            ('Ansible inventory file format not supported: {0}'
             ).format(extension))

    return [(host, {}, sorted(list(host_to_groups.get(host))))
            for host in host_to_groups]
示例#5
0
def make_names_data(image=None):
    if not image:
        raise InventoryError('No docker base image provided!')

    show_warning()

    # Save the image as the hostname, the image as data, @docker group
    yield '@docker/{0}'.format(image), {'docker_image': image}, ['@docker']
示例#6
0
def get_ansible_inventory(inventory_filename=None):
    if not inventory_filename:  # pragma: no cover
        raise InventoryError('No Ansible inventory filename provided!')

    if not path.exists(inventory_filename):
        raise InventoryError(('Could not find Ansible inventory file: {0}'
                              ).format(inventory_filename))

    logger.info('Parsing Ansible inventory...')

    config = ConfigParser(
        delimiters=(' '),  # we only handle the hostnames for now
        allow_no_value=True,  # we don't by default have = values
        interpolation=None,  # remove any Python interpolation
    )
    config.read(inventory_filename)
    return config
示例#7
0
def make_names_data(limit=None):
    vagrant_ssh_info = get_vagrant_config(limit)

    logger.debug("Got Vagrant SSH info: \n%s", vagrant_ssh_info)

    hosts = []
    current_host = None

    for line in vagrant_ssh_info:
        # Vagrant outputs an empty line between each host
        if not line:
            if current_host:
                hosts.append(_make_name_data(current_host))

            current_host = None
            continue

        key, value = line.split(" ", 1)

        if key == "Host":
            if current_host:
                hosts.append(_make_name_data(current_host))

            # Set the new host
            current_host = {
                key: value,
            }

        elif current_host:
            current_host[key] = value

        else:
            logger.debug("Extra Vagrant SSH key/value (%s=%s)", key, value)

    if current_host:
        hosts.append(_make_name_data(current_host))

    if not hosts:
        if limit:
            raise InventoryError(
                "No running Vagrant instances matching `{0}` found!".format(
                    limit))
        raise InventoryError("No running Vagrant instances found!")

    return hosts
示例#8
0
文件: chroot.py 项目: weakish/pyinfra
def make_names_data(directory=None):
    if not directory:
        raise InventoryError('No directory provided!')

    show_warning()

    yield '@chroot/{0}'.format(directory), {
        'chroot_directory': '/{0}'.format(directory.lstrip('/')),
    }, ['@chroot']
示例#9
0
def make_names_data(directory=None):
    if not directory:
        raise InventoryError("No directory provided!")

    show_warning()

    yield "@chroot/{0}".format(directory), {
        "chroot_directory": "/{0}".format(directory.lstrip("/")),
    }, ["@chroot"]
示例#10
0
def make_names_data(host_image_str):
    try:
        hostname, image = host_image_str.split(":", 1)
    except (AttributeError, ValueError):  # failure to parse the host_image_str
        raise InventoryError("No ssh host or docker base image provided!")

    if not image:
        raise InventoryError("No docker base image provided!")

    show_warning()

    yield (
        "@dockerssh/{0}:{1}".format(hostname, image),
        {
            "ssh_hostname": hostname,
            "docker_image": image
        },
        ["@dockerssh"],
    )
示例#11
0
def make_names_data(output_key=None):
    show_warning()

    if not output_key:
        raise InventoryError("No Terraform output key!")

    with progress_spinner({"fetch terraform output"}):
        tf_output_raw = local.shell("terraform output -json")

    tf_output = json.loads(tf_output_raw)
    tf_output = _flatten_dict(tf_output)

    if output_key not in tf_output:
        raise InventoryError(f"No Terraform output with key: `{output_key}`")

    tf_output_value = tf_output[output_key]
    if not isinstance(tf_output_value, list):
        raise InventoryError(
            f"Invalid Terraform output type, should be list, got `{type(tf_output_value)}`",
        )

    for ssh_target in tf_output_value:
        data = {"ssh_hostname": ssh_target}
        yield "@terraform/{0}".format(ssh_target), data, ["@terraform"]
示例#12
0
def make_names_data(limit=None):
    vagrant_ssh_info = get_vagrant_config(limit)

    logger.debug('Got Vagrant SSH info: \n{0}'.format(vagrant_ssh_info))

    hosts = []
    current_host = None

    for line in vagrant_ssh_info:
        # Vagrant outputs an empty line between each host
        if not line:
            if current_host:
                hosts.append(_make_name_data(current_host))

            current_host = None
            continue

        key, value = line.split(' ', 1)

        if key == 'Host':
            if current_host:
                hosts.append(_make_name_data(current_host))

            # Set the new host
            current_host = {
                key: value,
            }

        elif current_host:
            current_host[key] = value

        else:
            logger.debug('Extra Vagrant SSH key/value ({0}={1})'.format(
                key,
                value,
            ))

    if current_host:
        hosts.append(_make_name_data(current_host))

    if not hosts:
        raise InventoryError('No running Vagrant instances found!')

    return hosts
示例#13
0
def make_names_data(limit=None):
    mech_ssh_info = get_mech_config(limit)

    logger.debug('Got Mech SSH info: \n{0}'.format(mech_ssh_info))

    hosts = []
    current_host = None

    for line in mech_ssh_info:
        if not line:
            if current_host:
                hosts.append(_make_name_data(current_host))

            current_host = None
            continue

        key, value = line.strip().split(' ', 1)

        if key == 'Host':
            if current_host:
                hosts.append(_make_name_data(current_host))

            # Set the new host
            current_host = {
                key: value,
            }

        elif current_host:
            current_host[key] = value

        else:
            logger.debug('Extra Mech SSH key/value ({0}={1})'.format(
                key,
                value,
            ))

    if current_host:
        hosts.append(_make_name_data(current_host))

    if not hosts:
        raise InventoryError('No running Mech instances found!')

    return hosts
示例#14
0
def make_names_data(hostname=None):
    if hostname is not None:
        raise InventoryError('Cannot have more than one @local')

    yield '@local', {}, ['@local']
示例#15
0
def make_names_data(_=None):
    if _ is not None:
        raise InventoryError("Cannot have more than one @local")

    yield "@local", {}, ["@local"]
示例#16
0
def make_names_data(image=None):
    if not image:
        raise InventoryError('No docker base image provided!')

    # Save the image as the hostname, no data, @docker group
    yield image, {}, ['@docker']