Last active
March 8, 2024 12:01
-
-
Save dudil/72c930b0b7e33881a01673fd11c77ec3 to your computer and use it in GitHub Desktop.
This gist will show you how to use the 1password CLI to inject references into a toml file, and then use the OPToml class to read the toml file with the 1password references.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import shlex | |
import subprocess | |
import tomllib as toml | |
from pathlib import Path | |
from typing import Any | |
class OPToml: | |
""" | |
A wrapper around the tomlib.toml library to inject 1password references into the toml file | |
for more information about 1password references, see: https://developer.1password.com/docs/cli/secret-references/ | |
:param toml_file: Path to the toml file | |
:type toml_file: Path | |
""" | |
def __init__(self, toml_file: Path): | |
# Validate that the toml_file is existing file with .toml extension | |
if not toml_file.exists() or not toml_file.is_file() or toml_file.suffix.lower() != ".toml": | |
err_msg = f"Invalid toml file path: {toml_file}" | |
raise ValueError(err_msg) | |
# Run op cli to inject references into the toml string | |
command = shlex.split(f"op inject -i {shlex.quote(str(toml_file))}") | |
process = subprocess.Popen( | |
command, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, | |
text=True, | |
) | |
output, error = process.communicate() | |
if error: | |
error_message = f"OP Error: {error}" | |
raise ValueError(error_message) | |
self.toml = toml.loads(output.strip()) | |
# Implement __getitem__ to mimic tomlib.toml usage | |
# for example: db_pwd = OPToml("config.toml")["db"]["pwd"] | |
def __getitem__(self, key: str) -> Any: | |
return self.toml[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment