Using ansible-vault to encrypt secrets for Python scripts?

Clarence Subia
2 min readSep 8, 2023
  1. Install ansible-vault on your Linux development box.
sudo apt install ansible-vault

2. Encrypt your keys using ansible-vault create or ansible-vault encrypted if you want to create your unencrypted file beforehand. Take note that the format of your file should be in YAML.

# Using ansible-vault create
ansible-vault create secrets.yml
New Vault password:
Confirm New Vault password:


# You will be redirected to your text editor VI / VIM.
# Sample setup below:

---
secret_key: "myfirstkey"
secret_token: "myfirsttoken"

# You can directly view this encrypted file
ansible-vault view secrets.yml

3. Now that we have our encrypted YAML file, we can use this in our Python scripts to hide secret keys, passwords, tokens, etc. But first we also need to install the ansible-vault library, do not confuse this with the ansible-vault that we installed on our Linux box on step 1.

# Install ansible-vault library
pip install ansible-vault

# Install getpass to be used for vault password user input
pip install getpass

4. Sample Python script to test out reading encrypted file from ansible-vault. The response is on a dictionary type so we need to access the keys you defined from your YAML file.

#!/usr/bin/env python3

from getpass import getpass
from ansible_vault import Vault

# Get user input to unlock secrets.yml vault
vault_pass = getpass(prompt="Enter vault password: ")
vault = Vault(vault_pass)

# Load the YAML file into a variable
data = vault.load(open('secrets.yml').read())

# How to access Keys inside of the secrets.yml
secret_key = data["secret_key"] # Equates to secret_key: "myfirstkey"
secret_token = data["secret_token"] # Equates to secret_token: "myfirsttoken"

5. Here’s another use case, in this script we are interacting with VirusTotal API and it requires token key for its calls.


# Add the api_key to your secrets.yml using:
ansible-vault edit secrets.yml

---
secret_key: "myfirstkey"
secret_token: "myfirsttoken"
api_key: "972287fda70c324310--- REDUCTED ---b7009bc75d9c97f50de8e9"
#!/usr/bin/env python3

import json

import argparse
import requests

from getpass import getpass
from ansible_vault import Vault


vault_pass = getpass(prompt="Enter vault password: ")
vault = Vault(vault_pass)
keys = vault.load(open('secrets.yml').read())

vt_base_url = f"https://www.virustotal.com/api/v3/files"

parser = argparse.ArgumentParser(description="A VirusToal File hash checker.")
parser.add_argument("--hash", required=True, help="File hash to be Checked.")
args = parser.parse_args()
hash = args.hash

session = requests.Session()
session.headers = {"X-Apikey": keys["api_token"]}


def get_result(hash):
response = session.get(url=f"{vt_base_url}/{hash}")
json_data = json.loads(response.text)
return json_data


if __name__ == "__main__":
attributes = get_result(hash=hash)["data"]["attributes"]

name = attributes["meaningful_name"]
file_type = attributes["type_description"]
file_type_tags = ",".join(attributes["type_tags"])
sha256 = attributes["sha256"]
md5 = attributes["md5"]
sha1 = attributes["sha1"]
reputation = attributes["reputation"]

print(f"Name: {name}")
print(f"File Type: {file_type}\nTags: {file_type_tags}")
print(f"\nHashes: \nSHA256: {sha256}\nSHA1: {sha1}\nMD5: {md5}")
print(f"Reputation: {reputation}")
# Sample Usage

$ python3 vt_scan.py --hash eb84a283ff58906786d63ffe43a8ff2728584428f5f7d9972c664f63f8790113
Enter vault password:

Name: 5_202210852862708848.xls
File Type: MS Excel Spreadsheet
Tags: document,msoffice,spreadsheet,excel,xls

Hashes:
SHA256: eb84a283ff58906786d63ffe43a8ff2728584428f5f7d9972c664f63f8790113
SHA1: 9230520c6dd215e2152bb2e56b2a5d6b45ae8e13
MD5: d3032968085db665381d9cbd3569f330
Reputation: -99

References:

https://pypi.org/project/ansible-vault/
https://yaml.org/
https://www.virustotal.com/
https://docs.ansible.com/ansible/latest/vault_guide/index.html

--

--