Skip to content

Nautobot Plugin Nornir Credentials

nautobot_plugin_nornir.plugins.credentials

Init file for credentials.

env_vars

Credentials class for environment variables passwords.

CredentialsEnvVars

Bases: MixinNautobotORMCredentials

Credentials Class designed to work with Nautobot ORM.

This class is the default class that will return the same login and password for all devices based on the values of the environment variables

Source code in nautobot_plugin_nornir/plugins/credentials/env_vars.py
class CredentialsEnvVars(MixinNautobotORMCredentials):
    """Credentials Class designed to work with Nautobot ORM.

    This class is the default class that will return the same login and password
    for all devices based on the values of the environment variables
    """

    def __init__(self, params=None):
        """Initialize Credentials Class designed to work with Nautobot ORM.

        Args:
            params ([dict], optional): Credentials Parameters
        """
        if not params:
            params = {}

        if not isinstance(params, dict):
            raise TypeError("params must be a dictionary")

        self.username = os.getenv(params.get("username", USERNAME_ENV_VAR_NAME))
        self.password = os.getenv(params.get("password", PASSWORD_ENV_VAR_NAME))
        self.secret = os.getenv(params.get("secret", SECRET_ENV_VAR_NAME))

        if not self.secret:
            self.secret = self.password
__init__(params=None)

Initialize Credentials Class designed to work with Nautobot ORM.

Parameters:

Name Type Description Default
params [dict]

Credentials Parameters

None
Source code in nautobot_plugin_nornir/plugins/credentials/env_vars.py
def __init__(self, params=None):
    """Initialize Credentials Class designed to work with Nautobot ORM.

    Args:
        params ([dict], optional): Credentials Parameters
    """
    if not params:
        params = {}

    if not isinstance(params, dict):
        raise TypeError("params must be a dictionary")

    self.username = os.getenv(params.get("username", USERNAME_ENV_VAR_NAME))
    self.password = os.getenv(params.get("password", PASSWORD_ENV_VAR_NAME))
    self.secret = os.getenv(params.get("secret", SECRET_ENV_VAR_NAME))

    if not self.secret:
        self.secret = self.password

nautobot_orm

Credentials class designed to work with Nautobot ORM.

MixinNautobotORMCredentials

Bases: NautobotORMCredentials

Abstract Credentials Class mixin, to provide base get_device_creds functionality.

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_orm.py
class MixinNautobotORMCredentials(NautobotORMCredentials):
    """Abstract Credentials Class mixin, to provide base get_device_creds functionality."""

    def get_device_creds(self, device):
        """Return the credentials for a given device.

        Args:
            device (dcim.models.Device): Nautobot device object

        Return:
            username (string):
            password (string):
            secret (string):
        """
        return (self.username, self.password, self.secret)  # pylint: disable=no-member
get_device_creds(device)

Return the credentials for a given device.

Parameters:

Name Type Description Default
device Device

Nautobot device object

required
Return

username (string): password (string): secret (string):

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_orm.py
def get_device_creds(self, device):
    """Return the credentials for a given device.

    Args:
        device (dcim.models.Device): Nautobot device object

    Return:
        username (string):
        password (string):
        secret (string):
    """
    return (self.username, self.password, self.secret)  # pylint: disable=no-member

NautobotORMCredentials

Abstract Credentials Class designed to work with Nautobot ORM.

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_orm.py
class NautobotORMCredentials:
    """Abstract Credentials Class designed to work with Nautobot ORM."""

    def get_device_creds(self, device):  # pylint: disable=unused-argument
        """Return the credentials for a given device.

        Args:
            device (dcim.models.Device): Nautobot device object

        Return:
            username (string):
            password (string):
            secret (string):
        """
        return (None, None, None)

    def get_group_creds(self, group_name):  # pylint: disable=unused-argument
        """Return the credentials for a given group.

        Args:
            group_name (string): Name of the group

        Return:
            string: username
            string: password
            string: secret
        """
        return (None, None, None)
get_device_creds(device)

Return the credentials for a given device.

Parameters:

Name Type Description Default
device Device

Nautobot device object

required
Return

username (string): password (string): secret (string):

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_orm.py
def get_device_creds(self, device):  # pylint: disable=unused-argument
    """Return the credentials for a given device.

    Args:
        device (dcim.models.Device): Nautobot device object

    Return:
        username (string):
        password (string):
        secret (string):
    """
    return (None, None, None)
get_group_creds(group_name)

Return the credentials for a given group.

Parameters:

Name Type Description Default
group_name string

Name of the group

required
Return

string: username string: password string: secret

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_orm.py
def get_group_creds(self, group_name):  # pylint: disable=unused-argument
    """Return the credentials for a given group.

    Args:
        group_name (string): Name of the group

    Return:
        string: username
        string: password
        string: secret
    """
    return (None, None, None)

nautobot_secrets

Credentials class designed to work with Nautobot Secrets Functionality.

Nautobot Secrets Feature:

secret-group

secret: username - Because of templating can be n number of actual values. secret: password - Because of templating can be n number of actual values. secret: secret - Because of templating can be n number of actual values.

Caching Solution:

creds_cache = { "hashed key": "value" }

- "hashed key" is the rendred.parameter which is post template rendered secret key.
- "value" is the literal secrets value.

CredentialsNautobotSecrets

Bases: MixinNautobotORMCredentials

Credentials Class designed to work with Nautobot Secrets Functionality.

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_secrets.py
class CredentialsNautobotSecrets(MixinNautobotORMCredentials):
    """Credentials Class designed to work with Nautobot Secrets Functionality."""

    def __init__(self):
        """Initialize class with empty creds_cache."""
        self._creds_cache = {}

    def _get_or_cache_secret_key(self, device, sec):
        """Check if secret_key is already in cache, if not call setter method to add the entry.

        Args:
            device (dcim.Device): Nautobot Device object.
            sec (extra.SecretGroup): Nautobot SecretGroup objects.

        Returns:
            str: A rendered secgret group hashed into a single hashed id to use as a unique key.

        Examples:
            >>> # Example of a Environment Variable rendered.
            >>> device = Device.objects.first()
            >>> sec = device.secrets_group.secrets.last()
            >>> sec
            >>> <Secret: router-u>
            >>> sec.rendered_parameters(obj=device)
            >>> {'variable': 'DEVICE_ROUTER_USERNAME'}
            >>> str(hash(json.dumps(sec.rendered_parameters(obj=device), sort_keys=True)))
            >>> '588946476233721127'
            >>>
            >>> # Example using hashicorp vault secrets provider backend.
            >>> sec = device.secrets_group.secrets.first()
            >>> sec.rendered_parameters(obj=device)
            >>>
            {'key': 'username',
            'path': 'goldenconfig',
            'kv_version': 'v2',
            'mount_point': 'secret'}
            >>> str(hash(json.dumps(sec.rendered_parameters(obj=device), sort_keys=True)))
            >>> '-3888945057722956687'
        """
        # hash the rendered secrets params.
        secret_key_hash = str(hash(json.dumps(sec.rendered_parameters(obj=device), sort_keys=True)))
        if not self.creds_cache.get(secret_key_hash):
            # If hashed value isn't in the cache, then call actual get_value to pull secret value itself and
            # Update the cache property.
            self.creds_cache = {secret_key_hash: sec.get_value(obj=device)}
        return secret_key_hash

    @property
    def creds_cache(self):
        """
        Getter for in memory creds cache. This is useds to temporarily cache secrets-group creds to avoid re-querying secrets providers over and over per device if the same secret-group was used.

        Example:
            {"123435": 'supersecret'}
        """
        return self._creds_cache

    @creds_cache.setter
    def creds_cache(self, new_cred):
        """
        Setter for creds_cache.

        Args:
            new_cred (dict): new secret group key and values.
        """
        self._creds_cache.update(new_cred)

    def get_device_creds(self, device):
        """Return the credentials for a given device.

        Args:
            device (dcim.models.Device): Nautobot device object

        Return:
            username (string):
            password (string):
            secret (string):
        """
        if device.secrets_group:
            self.secret = None
            for sec in device.secrets_group.secrets.all():
                secret_value = self.creds_cache.get(self._get_or_cache_secret_key(device, sec))
                current_secret_type = getattr(
                    SecretsGroupSecretTypeChoices, f"TYPE_{sec.secrets_group_associations.first().secret_type.upper()}"
                )
                current_access_type = getattr(
                    SecretsGroupAccessTypeChoices, f"TYPE_{sec.secrets_group_associations.first().access_type.upper()}"
                )
                configured_access_type = _get_access_type_value(device)
                if (
                    current_secret_type == SecretsGroupSecretTypeChoices.TYPE_USERNAME
                    and configured_access_type == current_access_type
                ):
                    self.username = secret_value
                if (
                    current_secret_type == SecretsGroupSecretTypeChoices.TYPE_PASSWORD
                    and configured_access_type == current_access_type
                ):
                    self.password = secret_value
                if (
                    current_secret_type == SecretsGroupSecretTypeChoices.TYPE_SECRET
                    and configured_access_type == current_access_type
                ):
                    self.secret = secret_value
            if not self.secret:
                self.secret = self.password
            return (self.username, self.password, self.secret)
        return (None, None, None)
creds_cache property writable

Getter for in memory creds cache. This is useds to temporarily cache secrets-group creds to avoid re-querying secrets providers over and over per device if the same secret-group was used.

Example

{"123435": 'supersecret'}

__init__()

Initialize class with empty creds_cache.

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_secrets.py
def __init__(self):
    """Initialize class with empty creds_cache."""
    self._creds_cache = {}
get_device_creds(device)

Return the credentials for a given device.

Parameters:

Name Type Description Default
device Device

Nautobot device object

required
Return

username (string): password (string): secret (string):

Source code in nautobot_plugin_nornir/plugins/credentials/nautobot_secrets.py
def get_device_creds(self, device):
    """Return the credentials for a given device.

    Args:
        device (dcim.models.Device): Nautobot device object

    Return:
        username (string):
        password (string):
        secret (string):
    """
    if device.secrets_group:
        self.secret = None
        for sec in device.secrets_group.secrets.all():
            secret_value = self.creds_cache.get(self._get_or_cache_secret_key(device, sec))
            current_secret_type = getattr(
                SecretsGroupSecretTypeChoices, f"TYPE_{sec.secrets_group_associations.first().secret_type.upper()}"
            )
            current_access_type = getattr(
                SecretsGroupAccessTypeChoices, f"TYPE_{sec.secrets_group_associations.first().access_type.upper()}"
            )
            configured_access_type = _get_access_type_value(device)
            if (
                current_secret_type == SecretsGroupSecretTypeChoices.TYPE_USERNAME
                and configured_access_type == current_access_type
            ):
                self.username = secret_value
            if (
                current_secret_type == SecretsGroupSecretTypeChoices.TYPE_PASSWORD
                and configured_access_type == current_access_type
            ):
                self.password = secret_value
            if (
                current_secret_type == SecretsGroupSecretTypeChoices.TYPE_SECRET
                and configured_access_type == current_access_type
            ):
                self.secret = secret_value
        if not self.secret:
            self.secret = self.password
        return (self.username, self.password, self.secret)
    return (None, None, None)

settings_vars

Credentials class for setting credentials.

CredentialsSettingsVars

Bases: MixinNautobotORMCredentials

Credentials Class designed to work with Nautobot ORM that comes from settings.

This class will return the same login and password for all devices based on the values within your settings.

Source code in nautobot_plugin_nornir/plugins/credentials/settings_vars.py
class CredentialsSettingsVars(MixinNautobotORMCredentials):
    """Credentials Class designed to work with Nautobot ORM that comes from settings.

    This class will return the same login and password for all devices based on the values
    within your settings.
    """

    def __init__(self, params=None):
        """Initialize Credentials Class designed to work with Nautobot ORM.

        Args:
            params ([dict], optional): Credentials Parameters
        """
        if not params:
            params = {}

        if not isinstance(params, dict):
            raise TypeError("params must be a dictionary")

        self.username = PLUGIN_CFG.get("username")
        self.password = PLUGIN_CFG.get("password")
        self.secret = PLUGIN_CFG.get("secret")

        if not self.secret:
            self.secret = self.password
__init__(params=None)

Initialize Credentials Class designed to work with Nautobot ORM.

Parameters:

Name Type Description Default
params [dict]

Credentials Parameters

None
Source code in nautobot_plugin_nornir/plugins/credentials/settings_vars.py
def __init__(self, params=None):
    """Initialize Credentials Class designed to work with Nautobot ORM.

    Args:
        params ([dict], optional): Credentials Parameters
    """
    if not params:
        params = {}

    if not isinstance(params, dict):
        raise TypeError("params must be a dictionary")

    self.username = PLUGIN_CFG.get("username")
    self.password = PLUGIN_CFG.get("password")
    self.secret = PLUGIN_CFG.get("secret")

    if not self.secret:
        self.secret = self.password