def load_inventory(config: Config, ) -> Inventory:
    InventoryPluginRegister.auto_register()
    inventory_plugin = InventoryPluginRegister.get_plugin(
        config.inventory.plugin)
    inv = inventory_plugin(**config.inventory.options).load()

    if config.inventory.transform_function:
        TransformFunctionRegister.auto_register()
        transform_function = TransformFunctionRegister.get_plugin(
            config.inventory.transform_function)
        for h in inv.hosts.values():
            transform_function(
                h, **(config.inventory.transform_function_options or {}))

    return inv
Exemplo n.º 2
0
def cli(
    ctx,
    config_file,
    dry_run,
    username,
    password,
    from_dict,
    connection_options,
    **kwargs,
):
    """
    Initialize nornir with a configuration file, with code
    or with a combination of both.
    """

    ctx.ensure_object(dict)

    try:

        TransformFunctionRegister.register("adapt_host_data", adapt_host_data)

        if from_dict:
            d = dict([
                _json_loads(i)
                for i in (value.split("=") for value in _get_lists(from_dict))
            ])
            cf = (None if not config_file or config_file == "None" or "null"
                  else config_file)
            ctx.obj["nornir"] = InitNornir(config_file=cf,
                                           dry_run=dry_run,
                                           **d)
        else:
            ctx.obj["nornir"] = InitNornir(config_file=config_file,
                                           dry_run=dry_run)

        defaults = ctx.obj["nornir"].inventory.defaults

        if username:
            defaults.username = username
        if password:
            defaults.password = password

        if connection_options:
            for param in ctx.obj["nornir"].inventory.hosts.values():
                param.connection_options = connection_options

        _pickle_to_hidden_file("temp.pkl", obj=ctx.obj["nornir"])

        # run show_inventory command
        if any(kwargs.values()):
            ctx.invoke(cmd_show_inventory.cli, **kwargs)

    except (ValueError, IndexError, TypeError, KeyError):
        raise ctx.fail(
            click.BadParameter(f"{ERROR_MESSAGE}", ).format_message(), )
    except (AttributeError):
        ctx.fail(f"File '{config_file}' is empty", )
    except (FileNotFoundError):
        raise ctx.fail(
            click.BadParameter(
                f"Path '{config_file}' does not exist",
                param_hint="'--config_file' / '-c'",
            ).format_message(), )
    except Exception as err:
        raise click.ClickException(err)
Exemplo n.º 3
0
        pass

    def load(self):
        return Inventory(
            hosts=Hosts({
                "h1": Host("h1"),
                "h2": Host("h2"),
                "h3": Host("h3")
            }),
            groups=Groups({"g1": Group("g1")}),
            defaults=Defaults(),
        )


InventoryPluginRegister.register("inventory-test", InventoryTest)
TransformFunctionRegister.register("transform_func", transform_func)
TransformFunctionRegister.register("transform_func_with_options",
                                   transform_func_with_options)


class Test(object):
    def test_InitNornir_bare(self):
        os.chdir("tests/inventory_data/")
        nr = InitNornir()
        os.chdir("../../")
        assert len(nr.inventory.hosts)
        assert len(nr.inventory.groups)

    def test_InitNornir_defaults(self):
        os.chdir("tests/inventory_data/")
        nr = InitNornir(inventory={"plugin": "inventory-test"})
InventoryPluginRegister.register('InventoryFromDict', InventoryFromDict)

inventory = {'SW1': {'hostname': '192.168.1.201', 'platform': 'ios'}}

os.mkdir('logs') if not os.path.isdir('logs') else None
os.mkdir('logs/devices') if not os.path.isdir('logs/devices') else None


def host_credentials(host, username, password):
    host.username = username
    host.password = password
    host.connection_options['netmiko'] = ConnectionOptions(
        extras={'secret': password})


TransformFunctionRegister.register('HostCredentials', host_credentials)

nr = InitNornir(
    runner={
        'plugin': 'threaded',
        'options': {
            'num_workers': multiprocessing.cpu_count()
        }
    },
    inventory={
        'plugin': 'InventoryFromDict',
        'transform_function': 'HostCredentials',
        'transform_function_options': {
            'username': '******',
            'password': '******'
        },
"""
export NORNIR_INVENTORY_TRANSFORM_FUNCTION=transform_func
"""
from nornir import InitNornir
from nornir.core.plugins.inventory import TransformFunctionRegister


def transform_ansible(host):
    if "nxos" == host.groups[0].name:
        napalm_params = host.get_connection_parameters("napalm")
        napalm_params.port = 8443
        host.connection_options["napalm"] = napalm_params


def main():
    nr = InitNornir(config_file="config_transform.yaml")
    napalm_params = nr.inventory.hosts["nxos1"].get_connection_parameters(
        "napalm")

    napalm_params = nr.inventory.hosts["nxos1"].get_connection_parameters(
        "napalm")
    print(napalm_params.dict())


if __name__ == "__main__":
    TransformFunctionRegister.register("transform_func", transform_ansible)
    main()
Exemplo n.º 6
0
    },
    "SW-8": {
        "username": "******",
        "password": "******"
    },
    "SW-9": {
        "username": "******",
        "password": "******"
    },
    "SW-10": {
        "username": "******",
        "password": "******"
    },
    "SW-11": {
        "username": "******",
        "password": "******"
    },
    "SW-12": {
        "username": "******",
        "password": "******"
    }
}


def adapt_user_password(host):
    host.username = creds[f"{host}"]["username"]
    host.password = creds[f"{host}"]["password"]


TransformFunctionRegister.register("my_transfer_function", adapt_user_password)
"""
export NORNIR_INVENTORY_TRANSFORM_FUNCTION=transform_func
"""
import os
from nornir import InitNornir
from nornir.core.plugins.inventory import TransformFunctionRegister


def transform_automation_user(host):
    host.username = "******"
    host.password = os.environ.get("AUTOMATION_USER_PASSWORD", "bogus")


def main():
    nr = InitNornir(config_file="config_transform.yaml")
    print(f"{nr.inventory.hosts['srx2'].username}")


if __name__ == "__main__":
    TransformFunctionRegister.register("transform_func",
                                       transform_automation_user)
    main()