|
| 1 | +# Copyright 2019 Adobe. All rights reserved. |
| 2 | +# This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. You may obtain a copy |
| 4 | +# of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 5 | + |
| 6 | +# Unless required by applicable law or agreed to in writing, software distributed under |
| 7 | +# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 8 | +# OF ANY KIND, either express or implied. See the License for the specific language |
| 9 | +# governing permissions and limitations under the License. |
| 10 | + |
| 11 | +import os |
| 12 | +import logging |
| 13 | +import hvac |
| 14 | + |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +class SimpleVault: |
| 20 | + def __init__(self): |
| 21 | + pass |
| 22 | + |
| 23 | + def get_vault_client(self): |
| 24 | + url = os.getenv('VAULT_ADDR') |
| 25 | + namespace = os.getenv('VAULT_NAMESPACE') |
| 26 | + username = os.getenv('VAULT_USERNAME') |
| 27 | + password = os.getenv('VAULT_PASSWORD') |
| 28 | + logger.info("Vault using url: {}, namespace: {}, username: {}".format(url, namespace, username)) |
| 29 | + |
| 30 | + client = hvac.Client( |
| 31 | + url=url, |
| 32 | + namespace=namespace, |
| 33 | + ) |
| 34 | + |
| 35 | + try: |
| 36 | + client.auth.ldap.login( |
| 37 | + username=username, |
| 38 | + password=password, |
| 39 | + ) |
| 40 | + assert client.is_authenticated() |
| 41 | + logger.info("Vault LDAP authenticated") |
| 42 | + except Exception as e: |
| 43 | + raise Exception("Error authenticating Vault over LDAP") |
| 44 | + |
| 45 | + return client |
| 46 | + |
| 47 | + def get_token(self, policy): |
| 48 | + role = os.getenv('VAULT_ROLE') |
| 49 | + client = self.get_vault_client() |
| 50 | + logger.info("Generating token for policy: {} using role: {}".format(policy, role)) |
| 51 | + |
| 52 | + token = client.create_token( |
| 53 | + policies=[policy], |
| 54 | + role=role, |
| 55 | + lease='24h', |
| 56 | + ) |
| 57 | + |
| 58 | + return token['auth']['client_token'] |
0 commit comments