get_key.py 1.88 KB
Newer Older
1
2
3
4
5
#!/usr/bin/python3

import json
import os
import sys
6
7
8
9
from contextlib import contextmanager
from enum import Enum
from pathlib import Path
from typing import List
10
import click
11
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
37
38
39
40
41
42
import yaml


@contextmanager
def chdir(path):
    oldcwd = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(oldcwd)


root = Path(__file__).resolve().parents[1]

with chdir(root):
    from ansible.cli import CLI
    from ansible.constants import DEFAULT_VAULT_IDENTITY_LIST
    from ansible.parsing.dataloader import DataLoader
    from ansible.parsing.vault import VaultLib

    data_loader = DataLoader()
    data_loader.set_basedir(root)

    vault_lib = VaultLib(
        CLI.setup_vault_secrets(
            data_loader, DEFAULT_VAULT_IDENTITY_LIST, auto_prompt=False
        )
    )


def load_vault(path):
43
44
45
    return yaml.load(
        vault_lib.decrypt(Path(path).read_text()), Loader=yaml.SafeLoader
    )
46
47


48
class OutputFormat(str, Enum):
49
50
51
52
53
54
55
    BARE = "bare"
    ENV = "env"
    JSON = "json"

    def __str__(self):
        return self.value

56
57
58
59
60
@click.command()
@click.argument('vault', type=click.Path(exists=True))
@click.argument('keys', nargs=-1)
@click.option('--format', default=OutputFormat.BARE, type=click.Choice([e.value for e in OutputFormat]), help='Output format')
def main(vault, keys, format):
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    """
    Get a bunch of entries from the vault located at VAULT.

    Use KEYS to choose which keys in the vault you want to output.
    """
    vault = load_vault(vault)
    filtered = {vault_key: vault[vault_key] for vault_key in keys}

    if format == OutputFormat.BARE:
        for secret in filtered.values():
            print(secret)
    elif format == OutputFormat.ENV:
        for key, secret in filtered.items():
            print(f"{key}={secret}")
    elif format == OutputFormat.JSON:
        json.dump(filtered, sys.stdout)
77
78
79
80
        print()


if __name__ == "__main__":
81
    main()