feat(playbook): vault deployment is smooth-ish, unseals and initialize cluster as needed

This commit is contained in:
Bertrand Lanson 2023-12-29 23:40:34 +01:00
parent 29d906bcd2
commit 97a4752dbe
4 changed files with 41 additions and 40 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
**/__pycache__ **/__pycache__
.vscode .vscode
roles/ednxzu.* roles/ednxzu.*
etc*

View File

@ -15,8 +15,11 @@
key_shares: 3 key_shares: 3
key_threshold: 2 key_threshold: 2
run_once: true run_once: true
retries: 5
delay: 5
delegate_to: "{{ groups['vault_servers'] | first }}" delegate_to: "{{ groups['vault_servers'] | first }}"
register: _vault_init_secret register: _vault_init_secret
until: not _vault_init_secret.failed
- name: "Write vault configuration to file" - name: "Write vault configuration to file"
ansible.builtin.copy: ansible.builtin.copy:
@ -46,7 +49,7 @@
api_url: "http://127.0.0.1:8200" api_url: "http://127.0.0.1:8200"
key_shares: "{{ _vault_cluster_config['keys'] }}" key_shares: "{{ _vault_cluster_config['keys'] }}"
max_retries: "{{ (_vault_cluster_config['keys'] | length) - 1 }}" max_retries: "{{ (_vault_cluster_config['keys'] | length) - 1 }}"
retries: 5
- name: "Debug" delay: 5
ansible.builtin.debug: register: _unseal_status
msg: "{{ _vault_cluster_config }}" until: not _unseal_status.failed

View File

@ -11,7 +11,7 @@ deployment_method: "docker"
api_interface: "eth0" api_interface: "eth0"
api_interface_address: "{{ ansible_facts[api_interface]['ipv4']['address'] }}" api_interface_address: "{{ ansible_facts[api_interface]['ipv4']['address'] }}"
configuration_directory: "/tmp/hashistack" configuration_directory: "{{ lookup('env', 'PWD') }}/etc/hashistack"
########################## ##########################
# Support options ######## # Support options ########
@ -93,7 +93,7 @@ default_container_extra_volumes:
- "/etc/localtime:/etc/localtime" - "/etc/localtime:/etc/localtime"
hashi_vault_start_service: true hashi_vault_start_service: true
hashi_vault_version: latest hashi_vault_version: "1.15.2"
hashi_vault_deploy_method: "{{ deployment_method }}" # deployment method, either host or docker hashi_vault_deploy_method: "{{ deployment_method }}" # deployment method, either host or docker
hashi_vault_env_variables: {} hashi_vault_env_variables: {}
hashi_vault_data_dir: "/opt/vault" hashi_vault_data_dir: "/opt/vault"

View File

@ -1,9 +1,10 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import (absolute_import, division, print_function) from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
DOCUMENTATION = r''' DOCUMENTATION = r"""
--- ---
module: my_test module: my_test
@ -33,9 +34,9 @@ options:
author: author:
- Your Name (@yourGitHubHandle) - Your Name (@yourGitHubHandle)
''' """
EXAMPLES = r''' EXAMPLES = r"""
# Pass in a message # Pass in a message
- name: Test with a message - name: Test with a message
my_namespace.my_collection.my_test: my_namespace.my_collection.my_test:
@ -51,9 +52,9 @@ EXAMPLES = r'''
- name: Test failure of the module - name: Test failure of the module
my_namespace.my_collection.my_test: my_namespace.my_collection.my_test:
name: fail me name: fail me
''' """
RETURN = r''' RETURN = r"""
# These are examples of possible return values, and in general should use other names for return values. # These are examples of possible return values, and in general should use other names for return values.
original_message: original_message:
description: The original name param that was passed in. description: The original name param that was passed in.
@ -65,8 +66,7 @@ message:
type: str type: str
returned: always returned: always
sample: 'goodbye' sample: 'goodbye'
''' """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
import traceback import traceback
@ -79,46 +79,41 @@ else:
HVAC_IMPORT_ERROR = None HVAC_IMPORT_ERROR = None
HAS_HVAC = True HAS_HVAC = True
def run_module(): def run_module():
module_args = dict( module_args = dict(
api_url=dict(type='str', required=True), api_url=dict(type="str", required=True),
key_shares=dict(type='list', required=False, default=[]), key_shares=dict(type="list", required=False, default=[]),
max_retries=dict(type='int', required=False, default=3) max_retries=dict(type="int", required=False, default=3),
) )
result = dict( result = dict(changed=False, original_message="", state=None)
changed=False,
original_message='',
state=''
)
module = AnsibleModule( module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
argument_spec=module_args,
supports_check_mode=True
)
# Check if hvac module is available if not HAS_HVAC:
try:
import hvac
except ImportError:
module.fail_json( module.fail_json(
msg="Missing required library: hvac", msg="Missing required library: hvac", exception=HVAC_IMPORT_ERROR
exception=HVAC_IMPORT_ERROR
) )
if module.check_mode: if module.check_mode:
module.exit_json(**result) module.exit_json(**result)
# Initialize HashiCorp Vault client # Initialize HashiCorp Vault client
client = hvac.Client( client = hvac.Client(url=module.params["api_url"])
url=module.params['api_url']
) # Check if Vault is sealed
if not client.sys.is_sealed():
module.exit_json(**result)
# Unseal Vault # Unseal Vault
try: try:
retries = 0 retries = 0
while client.sys.is_sealed() and retries < module.params['max_retries']: vault_unseal_result = None
key_share = module.params['key_shares'][min(retries, len(module.params['key_shares']) - 1)] while client.sys.is_sealed() and retries < module.params["max_retries"]:
key_share = module.params["key_shares"][
min(retries, len(module.params["key_shares"]) - 1)
]
vault_unseal_result = client.sys.submit_unseal_key(key_share) vault_unseal_result = client.sys.submit_unseal_key(key_share)
retries += 1 retries += 1
except hvac.exceptions.VaultError as ve: except hvac.exceptions.VaultError as ve:
@ -128,13 +123,15 @@ def run_module():
if client.sys.is_sealed(): if client.sys.is_sealed():
module.fail_json(msg="Vault unsealing failed: Maximum retries reached.") module.fail_json(msg="Vault unsealing failed: Maximum retries reached.")
result['state'] = vault_unseal_result result["state"] = vault_unseal_result
result['changed'] = True result["changed"] = True
module.exit_json(**result) module.exit_json(**result)
def main(): def main():
run_module() run_module()
if __name__ == '__main__':
if __name__ == "__main__":
main() main()