Files
mtusi2026lab7/scripts/openbao-provision.py
2026-11-07 15:00:53 +03:00

55 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""Operator provisions certificate auth and scoped KV v2 paths; no credentials printed."""
import json
import os
from pathlib import Path
import ssl
import subprocess
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / 'secrets'
BASE = os.environ.get('BAO_OPERATOR_ADDR', 'https://localhost:18200').rstrip('/')
TLS = ssl.create_default_context(cafile=str(SECRETS / 'ca.crt'))
TOKEN = json.loads((SECRETS / 'openbao-operator.json').read_text())['root_token']
def call(path, body=None):
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(BASE + '/v1/' + path, data=data,
headers={'Content-Type': 'application/json', 'X-Vault-Token': TOKEN},
method='GET' if body is None else 'POST')
with urllib.request.urlopen(request, context=TLS, timeout=10) as response:
payload = response.read()
return json.loads(payload) if payload else {}
def main():
if 'cert/' not in call('sys/auth')['data']:
call('sys/auth/cert', {'type': 'cert'})
if 'lab/' not in call('sys/mounts')['data']:
call('sys/mounts/lab', {'type': 'kv', 'options': {'version': '2'}})
files = {'DATABASE_URL': 'database_api_url', 'CURSOR_SECRET': 'cursor_secret',
'S3_ACCESS_KEY_ID': 's3_access_key_id', 'S3_SECRET_ACCESS_KEY': 's3_secret_access_key',
'BROKER_URL': 'broker_api_url'}
for role in ('api', 'worker'):
role_files = dict(files)
if role == 'worker':
role_files.update(DATABASE_URL='database_worker_url',
S3_ACCESS_KEY_ID='s3_worker_access_key_id',
S3_SECRET_ACCESS_KEY='s3_worker_secret_access_key',
BROKER_URL='broker_worker_url')
values = {name: (SECRETS / file).read_text().strip() for name, file in role_files.items()}
policy = f'path "lab/data/{role}" {{ capabilities = ["read"] }}'
call('sys/policies/acl/' + role, {'policy': policy})
certificate = subprocess.check_output(['openssl', 'x509', '-in', str(SECRETS / ('bao-' + role + '.pem'))], text=True)
call('auth/cert/certs/' + role, {'certificate': certificate, 'token_policies': [role],
'token_ttl': '1h', 'token_max_ttl': '1h',
'token_no_default_policy': True})
call('lab/data/' + role, {'data': values})
print('Scoped API and worker policies, certificate identities and secret paths configured.')
if __name__ == '__main__':
main()