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`

    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    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`

    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    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`

    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    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`

    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    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`

     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    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`

     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    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
Source code in `nautobot_plugin_nornir/plugins/credentials/nautobot_orm.py`

    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    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

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`

     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    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 secrets_group_association in device.secrets_group.secrets_group_associations.all():
                    secret_value = self.creds_cache.get(
                        self._get_or_cache_secret_key(device, secrets_group_association.secret)
                    )
                    current_secret_type = secrets_group_association.secret_type
                    current_access_type = secrets_group_association.access_type
                    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`

    65
    66
    67
    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`

    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    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 secrets_group_association in device.secrets_group.secrets_group_associations.all():
                secret_value = self.creds_cache.get(
                    self._get_or_cache_secret_key(device, secrets_group_association.secret)
                )
                current_secret_type = secrets_group_association.secret_type
                current_access_type = secrets_group_association.access_type
                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`

     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    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`

    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    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