Don’t you hate when tutorials show you something and then say, “I’m just doing it this way for the tutorial,” or, “It’s my lab, so they don’t use best practices,” but never show you the proper way? One thing that always bothered me when I was starting out with network automation was tutorials that almost always used plain text passwords with a disclaimer: “This is my lab; don’t do this in production.” Yet, they never showed me how to properly store passwords in my automation code. So today, I’m sharing a few easy ways to do this:
1. Don’t hardcode your passwords: Use interactive prompts
Ansible: Use vars_prompt to ask for a password.
# playbook.yml
- name: Example playbook
hosts: localhost
vars_prompt:
- name: "password"
prompt: "Enter your password"
private: yes
tasks:
- name: Print password
debug:
msg: "Password is {{ password }}"
Python: Use getpass to securely prompt for a password.
# script.py
import getpass
password = getpass.getpass("Enter your password: ")
print(f"Password is {password}")
2. Environment variables: Store passwords in environment variables
Creating Environment Variables:
Linux:
export API_KEY="your-api-key"
export ZONE_ID="your-zone-id"
Windows:
$env:API_KEY="your-api-key"
$env:ZONE_ID="your-zone-id"
Ansible: Access environment variables using lookup.
# playbook.yml
- name: Example playbook
hosts : localhost
tasks:
- name: Print API key from environment variable
debug:
msg: "API Key is {{ lookup('env', 'API_KEY') }}"
Python: Use os.getenv to get environment variables.
# script.py
import os
api_key = os.getenv("API_KEY")
zone_id = os.getenv("ZONE_ID")
print(f"API Key is {api_key}")
print(f"Zone ID is {zone_id}")
3. Secrets management tools: Encrypt and include secure variable files
Ansible: Use Ansible Vault to encrypt a variable file and include it in a playbook. Create a vars file named vaultvars.yml
# vaultvars.yml (before encryption)
---
API_KEY="your-api-key"
Encrypt the variable file
ansible-vault encrypt vaultvars.yml
Include the vaultvars.yml in your playbook
# playbook.yml
- name: Example playbook with Vault
hosts: localhost
vars_files:
- vaultvars.yml
tasks:
- name: Print API key from vault
debug:
msg: "API Key is {{ API_key }}"
Use these methods, and you can enhance the security of your automation scripts and set a good example for others.