Package: blackdark-nautobot-secrets-providers
Nautobot Secrets ProvidersNautobot Secrets Providers is a plugin forNautobot1.2.0 or higher that bundles Secrets Providers for integrating with popular secrets backends. Nautobot 1.2.0 added support for integrating with retrieving secrets from various secrets providers.This plugin publishes secrets providers that are not included in the within the Nautobot core software package so that it will be easier to maintain and extend support for various secrets providers without waiting on Nautobot software releases.Supported Secrets BackendsThis plugin supports the following popular secrets backends:Secrets BackendSupported Secret TypesSupported Authentication MethodsAWS Secrets ManagerOther: Key/value pairsAWS credentials(see Usage section below)HashiCorp VaultK/V Version 2TokenAppRoleAWSKubernetesDelinea/Thycotic Secret ServerSecret Server CloudSecret Server (on-prem)Access Token AuthorizationDomain AuthorizationPassword AuthorizationScreenshotsInstallationNautobot Secrets Providers is compatible with Nautobot 1.2.0 and higher. Support for Thycotic Secret Server requires Python 3.7 or later.The package is available as a Python package in PyPI and can be installed withpip:pip install nautobot-secrets-providersYou may quickly install all of the dependent libraries using the following command, however, this isnot recommended for production deploymentsas it will install extras that you may not need:pip install nautobot-secrets-providers[all]DependenciesFor this plugin to operate you must install at least one of the dependent libraries required by the secrets providers.You must install the dependencies for at least one of the supported secrets providers or aRuntimeErrorwill be raised.AWS Secrets Manager, AWS System Manager Parameter StoreThe AWS Secrets Manager and Parameter Store providers require theboto3library. This can be easily installed along with the plugin using the following command:pip install nautobot-secrets-providers[aws]HashiCorp VaultThe HashiCorp Vault provider requires thehvaclibrary. This can easily be installed along with the plugin using the following command:pip install nautobot-secrets-providers[hashicorp]Delinea/Thycotic Secret ServerThe Delinea/Thycotic Secret Server provider requires thepython-tss-sdklibrary. This can easily be installed along with the plugin using the following command:pip install nautobot-secrets-providers[thycotic]Enabling Secrets ProvidersTo ensure Nautobot Secrets Providers is automatically re-installed during future upgrades, create a file namedlocal_requirements.txt(if not already existing) in the Nautobot root directory (alongsiderequirements.txt) and list thesecretspackage:echo nautobot-secrets-providers >> local_requirements.txtOnce installed, the plugin needs to be enabled in yournautobot_config.py:# In your nautobot_config.pyPLUGINS=["nautobot_secrets_providers"]# PLUGINS_CONFIG = {#   "nautobot_secrets_providers": {#      See below for how to configure Nautobot for each secrets provider!#   }# }UsageBefore you proceed, you must haveat least oneof the dependent libaries installed as detailed above.Please do not enable this plugin until you are able to install the dependencies, as it will block Nautobot from starting.AWS Secrets Manager, AWS System Manager Parameter StoreAuthenticationNo configuration is needed within Nautobot for this provider to operate. Instead you must provideAWS credentials in one of the methods supported by theboto3library.Boto3 credentials can be configured in multiple ways (eight as of this writing) that are mirrored here:Passing credentials as parameters in theboto.client()methodPassing credentials as parameters when creating a Session objectEnvironment variablesShared credential file (~/.aws/credentials)AWS config file (~/.aws/config)Assume Role providerBoto2 config file (/etc/boto.cfgand~/.boto)Instance metadata service on an Amazon EC2 instance that has an IAM role configured.The AWS Secrets Manager provider only supports methods 3-8. Methods 1 and 2 ARE NOT SUPPORTED at this time.We highly recommend you defer to using environment variables for your deployment as specified in the credentials documentation linked above. The values specified in the linked documentation should beset within your~.bashrc(or similar profile) on your system.ConfigurationThis is an example based on our recommended deployment pattern in the section above (item 3) that is usingenvironment variables. You will need to set these in the environment prior to starting Nautobot:export AWS_ACCESS_KEY_ID=foo      # The access key for your AWS account.
export AWS_SECRET_ACCESS_KEY=bar  # The secret key for your AWS account.Please refer to theNautobot documentation on updating your.bashrcfor how to do this for production Nautobot deployments.HashiCorp VaultConfigurationYou must provide a mapping inPLUGINS_CONFIGwithin yournautobot_config.py, for example:PLUGINS_CONFIG={"nautobot_secrets_providers":{"hashicorp_vault":{"url":"http://localhost:8200","auth_method":"token","token":os.getenv("NAUTOBOT_HASHICORP_VAULT_TOKEN"),}},}url- (required) The URL to the HashiCorp Vault instance (e.g.http://localhost:8200).auth_method- (optional / defaults to "token") The method used to authenticate against the HashiCorp Vault instance. Either"approle","aws","kubernetes"or"token".  For information on using AWS authentication with vault see theauthenticationsection above.ca_cert- (optional) Path to a PEM formatted CA certificate to use when verifying the Vault connection.  Can alternatively be set toFalseto ignore SSL verification (not recommended) orTrueto use the system certificates.default_mount_point- (optional / defaults to "secret") The default mount point of the K/V Version 2 secrets engine within Hashicorp Vault.k8s_token_path- (optional) Path to the kubernetes service account token file.  Defaults to "/var/run/secrets/kubernetes.io/serviceaccount/token".token- (optional) Required when"auth_method": "token"orauth_methodis not supplied. The token for authenticating the client with the HashiCorp Vault instance. As with other sensitive service credentials, we recommend that you provide the token value as an environment variable and retrieve it with{"token": os.getenv("NAUTOBOT_HASHICORP_VAULT_TOKEN")}rather than hard-coding it in yournautobot_config.py.role_name- (optional) Required when"auth_method": "kubernetes", optional when"auth_method": "aws".  The Vault Kubernetes role or Vault AWS role to assume which the pod's service account has access to.role_id- (optional) Required when"auth_method": "approle". As with other sensitive service credentials, we recommend that you provide the role_id value as an environment variable and retrieve it with{"role_id": os.getenv("NAUTOBOT_HASHICORP_VAULT_ROLE_ID")}rather than hard-coding it in yournautobot_config.py.secret_id- (optional) Required when"auth_method": "approle".As with other sensitive service credentials, we recommend that you provide the secret_id value as an environment variable and retrieve it with{"secret_id": os.getenv("NAUTOBOT_HASHICORP_VAULT_SECRET_ID")}rather than hard-coding it in yournautobot_config.py.login_kwargs- (optional) Additional optional parameters to pass to the login method forapprole,awsandkubernetesauthentication methods.Delinea/Thycotic Secret Server (TSS)The Delinea/Thycotic Secret Server plugin includes two providers:Thycotic Secret Server by IDThis provider uses theSecret IDto specifiy the secret that is selected. TheSecret IDis displayed in the browser's URL field if youEditthe data in Thycotic Secret Server.Example:The url is:https://pw.example.local/SecretServer/app/#/secret/**1234**/generalIn this example the value forSecret IDis1234.Thycotic Secret Server by PathThis provider allows to select the secret by folder-path and secret-name. The path delimiter is a '\'.TheSecret pathis displayed as page header whenEdita secret.Example:The header is:NET-Automation > Nautobot > My-SecretIn this example the value forSecret pathis\NET-Automation\Nautobot\My-Secret.ConfigurationPLUGINS_CONFIG={"nautobot_secrets_providers":{"thycotic":{# https://github.com/thycotic/python-tss-sdk"base_url":os.getenv("SECRET_SERVER_BASE_URL",None),"ca_bundle_path":os.getenv("REQUESTS_CA_BUNDLE",None),"cloud_based":is_truthy(os.getenv("SECRET_SERVER_IS_CLOUD_BASED","False")),"domain":os.getenv("SECRET_SERVER_DOMAIN",None),"password":os.getenv("SECRET_SERVER_PASSWORD",None),"tenant":os.getenv("SECRET_SERVER_TENANT",None),"token":os.getenv("SECRET_SERVER_TOKEN",None),"username":os.getenv("SECRET_SERVER_USERNAME",None),},}}base_url- (required) The Secret Server base_url.e.g.'https://pw.example.local/SecretServer'ca_bundle_path- (optional) When using self-signed certificates this variable must be set to a file containing the trusted certificates (in .pem format).e.g. '/etc/ssl/certs/ca-bundle.trust.crt'.cloud_based- (optional) Set to "True" if Secret Server Cloud should be used. (Default: "False").domain- (optional) Required for 'Domain Authorization'password- (optional) Required for 'Secret Server Cloud', 'Password Authorization', 'Domain Authorization'.tenant- (optional) Required for 'Domain Authorization'.token- (optional) Required for 'Access Token Authorization'.username- (optional) Required for 'Secret Server Cloud', 'Password Authorization', 'Domain Authorization'.ContributingPull requests are welcomed and automatically built and tested against multiple version of Python and multiple version of Nautobot through GitHub Actions.The project is packaged with a light development environment based ondocker-composeto help with the local development of the project and to run the tests within GitHub Actions.The project is following Network to Code software development guidelines and is leveraging:Black, Pylint, Bandit and pydocstyle for Python linting and formatting.Django unit test to ensure the plugin is working properly.Development EnvironmentThe development environment can be used in 2 ways. First, with a local poetry environment if you wish to develop outside of Docker with the caveat of using external services provided by Docker for PostgreSQL and Redis. Second, all services are spun up using Docker and a local mount so you can develop locally, but Nautobot is spun up within the Docker container.Below is a quick start guide if you're already familiar with the development environment provided, but if you're not familiar, please read theGetting Started Guide.InvokeThePyInvokelibrary is used to provide some helper commands based on the environment.  There are a few configuration parameters which can be passed to PyInvoke to override the default configuration:nautobot_ver: the version of Nautobot to use as a base for any built docker containers (default: 1.2.0)project_name: the default docker compose project name (default: nautobot_secrets_providers)python_ver: the version of Python to use as a base for any built docker containers (default: 3.7)local: a boolean flag indicating if invoke tasks should be run on the host or inside the docker containers (default: False, commands will be run in docker containers)compose_dir: the full path to a directory containing the project compose filescompose_files: a list of compose files applied in order (seeMultiple Compose filesfor more information)UsingPyInvokethese configuration options can be overridden usingseveral methods.  Perhaps the simplest is simply setting an environment variableINVOKE_NAUTOBOT_SECRETS_PROVIDERS_VARIABLE_NAMEwhereVARIABLE_NAMEis the variable you are trying to override.  The only exception iscompose_files, because it is a list it must be overridden in a yaml file.  There is an exampleinvoke.yml(invoke.example.yml) in this directory which can be used as a starting point.Local Poetry Development EnvironmentCopydevelopment/creds.example.envtodevelopment/creds.env(This file will be ignored by Git and Docker)Uncomment thePOSTGRES_HOST,REDIS_HOST, andNAUTOBOT_ROOTvariables indevelopment/creds.envCreate aninvoke.ymlfile with the following contents at the root of the repo (you can alsocp invoke.example.yml invoke.ymland edit as necessary):---nautobot_secrets_providers:local:truecompose_files:-"docker-compose.requirements.yml"Run the following commands:poetryshell
poetryinstall--extrasnautobotexport$(catdevelopment/dev.env|xargs)export$(catdevelopment/creds.env|xargs)invokestart&&sleep5nautobot-servermigrateIf you want to develop on the latest develop branch of Nautobot, run the following command:poetry add --optional git+https://github.com/nautobot/nautobot@develop. After the@symbol must match either a branch or a tag.You can now run nautobot-server commands as you would from theNautobot documentationfor example to start the development server:nautobot-serverrunserver0.0.0.0:8080--insecureNautobot server can now be accessed athttp://localhost:8080.It is typically recommended to launch the Nautobotrunservercommand in a separate shell so you can keep developing and manage the webserver separately.Docker Development EnvironmentThis project is managed byPython Poetryand has a few requirements to setup your development environment:Install Poetry, see thePoetry Documentationfor your operating system.Install Docker, see theDocker documentationfor your operating system.Once you have Poetry and Docker installed you can run the following commands to install all other development dependencies in an isolated python virtual environment:poetryshell
poetryinstall
invokestartNautobot server can now be accessed athttp://localhost:8080.To either stop or destroy the development environment use the following options.invoke stop- Stop the containers, but keep all underlying systems intactinvoke destroy- Stop and remove all containers, volumes, etc. (This results in data loss due to the volume being deleted)CLI Helper CommandsThe project is coming with a CLI helper based oninvoketo help setup the development environment. The commands are listed below in 3 categoriesdev environment,utilityandtesting.Each command can be executed withinvoke <command>. Environment variablesINVOKE_NAUTOBOT_SECRETS_PROVIDERS_PYTHON_VERandINVOKE_NAUTOBOT_SECRETS_PROVIDERS_NAUTOBOT_VERmay be specified to override the default versions. Each command also has its own helpinvoke <command> --helpDocker dev environmentbuild            Build all docker images.
  debug            Start Nautobot and its dependencies in debug mode.
  destroy          Destroy all containers and volumes.
  restart          Restart Nautobot and its dependencies.
  start            Start Nautobot and its dependencies in detached mode.
  stop             Stop Nautobot and its dependencies.Utilitycli              Launch a bash shell inside the running Nautobot container.
  create-user      Create a new user in django (default: admin), will prompt for password.
  makemigrations   Run Make Migration in Django.
  nbshell          Launch a nbshell session.Testingbandit           Run bandit to validate basic static code security analysis.
  black            Run black to check that Python files adhere to its style standards.
  flake8           This will run flake8 for the specified name and Python version.
  pydocstyle       Run pydocstyle to validate docstring formatting adheres to NTC defined standards.
  pylint           Run pylint code analysis.
  tests            Run all tests for this plugin.
  unittest         Run Django unit tests for the plugin.Project DocumentationProject documentation is generated bymkdocsfrom the documentation located in the docs folder.  You can configurereadthedocs.ioto point at this folder in your repo.  For development purposes adocker-compose.docs.ymlis also included.  A container hosting the docs will be started using the invoke commands onhttp://localhost:8001, as changes are saved the docs will be automatically reloaded.Developing Against Secrets BackendsAWS Secrets ManagerThis assumes you are logged into the AWS Console.Navigate to AWS ConsoleNavigate to AWS Secrets ManagerClick "Store a new secret"Select “Other type of secrets”Use Secret key/valueEnterhello=worldUse "DefaultEncryptionKey" for nowClick "Next"Under "Secret name" fill outhelloClick "Next"Under "Configure automatic rotation"Leave it as "Disable automatic rotation"On "Store a new secret"Copy the sample code (see below)Click "Store"ENDInstall the AWS CLINext, install theAWS CLI.On MacOS, this can be done usingbrew install awscli:brew install awscliOn Linux, you will need to run acurlcommand (This assumes x86. Please see the docs forAWS CLI on
Linuxfor ARM and other options):curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/installConfigure the AWS CLIAfter installing the AWS CLI, you will need to configure it for authentication.You may use an existing AWS access key or create a new one. For these instructions we cover the need to create a new access key that can be used for this.Navigate to AWS ConsoleClick your usernameClick "My security credentials"Click "create access key"Save your "Access key ID" and "Secret access key" for use when configuring the AWS CLINow configure the CLI:Runaws configureEnter your credentials from aboveChoose your regionUse output format:jsonExample:$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-east-2
Default output format [None]: jsonNow you are ready to use the sample code to retrieve your secret from AWS Secrets Manager!Sample CodeMake sure that theboto3client is installed:poetry install --extras awsNext, save this asaws_secrets.py:# Use this code snippet in your app.# If you need more information about configurations or implementing the sample code, visit the AWS docs:# https://aws.amazon.com/developers/getting-started/python/importboto3importbase64frombotocore.exceptionsimportClientErrordefget_secret():secret_name="hello"region_name="us-east-2"# Create a Secrets Manager clientsession=boto3.session.Session()client=session.client(service_name='secretsmanager',region_name=region_name)# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html# We rethrow the exception by default.try:get_secret_value_response=client.get_secret_value(SecretId=secret_name)exceptClientErrorase:ife.response['Error']['Code']=='DecryptionFailureException':# Secrets Manager can't decrypt the protected secret text using the provided KMS key.# Deal with the exception here, and/or rethrow at your discretion.raiseeelife.response['Error']['Code']=='InternalServiceErrorException':# An error occurred on the server side.# Deal with the exception here, and/or rethrow at your discretion.raiseeelife.response['Error']['Code']=='InvalidParameterException':# You provided an invalid value for a parameter.# Deal with the exception here, and/or rethrow at your discretion.raiseeelife.response['Error']['Code']=='InvalidRequestException':# You provided a parameter value that is not valid for the current state of the resource.# Deal with the exception here, and/or rethrow at your discretion.raiseeelife.response['Error']['Code']=='ResourceNotFoundException':# We can't find the resource that you asked for.# Deal with the exception here, and/or rethrow at your discretion.raiseeelse:# Decrypts secret using the associated KMS CMK.# Depending on whether the secret is a string or binary, one of these fields will be populated.if'SecretString'inget_secret_value_response:secret=get_secret_value_response['SecretString']else:decoded_binary_secret=base64.b64decode(get_secret_value_response['SecretBinary'])# Your code goes here.# ^ Above was generated by AWS.# This was added by us so you can run this as a script:if__name__=="__main__":secret=get_secret()print(f"Secret ={secret}")Run it withpython aws_secrets.py:$ python aws_secrets.py
Secret = {"hello":"world"}.Note that this blob is JSON and will also need to be decoded if you want to extract the value.HashiCorp VaultMake sure that thehvacclient is installed:poetry install --extras hashicorpStart Services with Dockerinvoke startSet an alias to work withvaultThis will allow you to easily run the CLI command from within the container:alias vault="docker exec -it nautobot_secrets_providers_vault_1 vault"Interact with the Vault vi CLI (viadocker execinto the container from localhost):$ vault status
Key             Value
---             -----
Seal Type       shamir
Initialized     true
Sealed          false
Total Shares    1
Threshold       1
Version         1.8.2
Storage Type    inmem
Cluster Name    vault-cluster-35c5d319
Cluster ID      2611f99c-a6de-a883-1fcc-bfffdc0217bc
HA Enabled      falseUsing the PythonhvacLibraryThis establishes a client, creates a basic key/value secret (hello=world) at the pathhello, and then retrieves the data from thehellokey at the secret pathhello.This is equivalent to the commandvault kv get -field hello secret/hello.In[1]:importhvacIn[2]:client=hvac.Client(url="http://localhost:8200",token="nautobot")In[3]:client.secrets.kv.create_or_update_secret(path="hello",secret=dict(hello="world"))Out[3]:{'request_id':'c4709868-c08f-4cb1-ab8c-605c58b82f3f','lease_id':'','renewable':False,'lease_duration':0,'data':{'created_time':'2021-09-16T23:21:07.5564132Z','deletion_time':'','destroyed':False,'version':2},'wrap_info':None,'warnings':None,'auth':None}In[4]:client.secrets.kv.read_secret(path="hello")["data"]["data"]["hello"]Out[4]:'world'QuestionsFor any questions or comments, please check theFAQfirst and feel free to swing by theNetwork to Code Slack workspace(channel#networktocode).