commit 42d0fa0da0278358d0e01fe85e7a56cf7f7c7df3 Author: Robert Kaussow Date: Sun Jul 30 22:49:18 2023 +0200 initial commit diff --git a/.drone.jsonnet b/.drone.jsonnet new file mode 100644 index 0000000..a986f25 --- /dev/null +++ b/.drone.jsonnet @@ -0,0 +1,159 @@ +local PipelineLinting = { + kind: 'pipeline', + name: 'linting', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + name: 'ansible-later', + image: 'thegeeklab/ansible-later', + commands: [ + 'ansible-later', + ], + }, + { + name: 'python-format', + image: 'python:3.9', + environment: { + PY_COLORS: 1, + }, + commands: [ + 'pip install -qq yapf', + '[ ! -z "$(find . -type f -name *.py)" ] && yapf -rd ./', + ], + }, + { + name: 'python-flake8', + image: 'python:3.9', + environment: { + PY_COLORS: 1, + }, + commands: [ + 'pip install -qq flake8', + 'flake8', + ], + }, + ], + trigger: { + ref: ['refs/heads/main', 'refs/tags/**', 'refs/pull/**'], + }, +}; + +local PipelineDeployment(scenario='rocky9') = { + kind: 'pipeline', + name: 'testing-' + scenario, + platform: { + os: 'linux', + arch: 'amd64', + }, + concurrency: { + limit: 1, + }, + workspace: { + base: '/drone/src', + path: '${DRONE_REPO_NAME}', + }, + steps: [ + { + name: 'ansible-molecule', + image: 'thegeeklab/molecule:3', + environment: { + HCLOUD_TOKEN: { from_secret: 'hcloud_token' }, + }, + commands: [ + 'molecule test -s ' + scenario, + ], + }, + ], + depends_on: [ + 'linting', + ], + trigger: { + ref: ['refs/heads/main', 'refs/tags/**', 'refs/pull/**'], + }, +}; + +local PipelineDocumentation = { + kind: 'pipeline', + name: 'documentation', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + name: 'generate', + image: 'thegeeklab/ansible-doctor', + environment: { + ANSIBLE_DOCTOR_LOG_LEVEL: 'INFO', + ANSIBLE_DOCTOR_FORCE_OVERWRITE: true, + ANSIBLE_DOCTOR_EXCLUDE_FILES: 'molecule/', + ANSIBLE_DOCTOR_TEMPLATE: 'hugo-book', + ANSIBLE_DOCTOR_ROLE_NAME: '${DRONE_REPO_NAME#*.}', + ANSIBLE_DOCTOR_OUTPUT_DIR: '_docs/', + }, + }, + { + name: 'publish', + image: 'plugins/gh-pages', + settings: { + remote_url: 'https://gitea.rknet.org/ansible/${DRONE_REPO_NAME}', + netrc_machine: 'gitea.rknet.org', + username: { from_secret: 'gitea_username' }, + password: { from_secret: 'gitea_token' }, + pages_directory: '_docs/', + target_branch: 'docs', + }, + when: { + ref: ['refs/heads/main'], + }, + }, + ], + trigger: { + ref: ['refs/heads/main', 'refs/tags/**', 'refs/pull/**'], + }, + depends_on: [ + 'testing-rocky9', + ], +}; + +local PipelineNotification = { + kind: 'pipeline', + name: 'notification', + platform: { + os: 'linux', + arch: 'amd64', + }, + clone: { + disable: true, + }, + steps: [ + { + name: 'matrix', + image: 'thegeeklab/drone-matrix', + settings: { + homeserver: { from_secret: 'matrix_homeserver' }, + roomid: { from_secret: 'matrix_roomid' }, + template: 'Status: **{{ .Build.Status }}**
Build: [{{ .Repo.Owner }}/{{ .Repo.Name }}]({{ .Build.Link }}){{ if .Build.Branch }} ({{ .Build.Branch }}){{ end }} by {{ .Commit.Author }}
Message: {{ .Commit.Message.Title }}', + username: { from_secret: 'matrix_username' }, + password: { from_secret: 'matrix_password' }, + }, + }, + ], + depends_on: [ + 'documentation', + ], + trigger: { + status: ['success', 'failure'], + ref: ['refs/heads/main', 'refs/tags/**'], + }, +}; + +[ + PipelineLinting, + PipelineDeployment(scenario='rocky9'), + PipelineDocumentation, + PipelineNotification, +] diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..5c9c734 --- /dev/null +++ b/.drone.yml @@ -0,0 +1,153 @@ +--- +kind: pipeline +name: linting + +platform: + os: linux + arch: amd64 + +steps: + - name: ansible-later + image: thegeeklab/ansible-later + commands: + - ansible-later + + - name: python-format + image: python:3.9 + commands: + - pip install -qq yapf + - "[ ! -z \"$(find . -type f -name *.py)\" ] && yapf -rd ./" + environment: + PY_COLORS: 1 + + - name: python-flake8 + image: python:3.9 + commands: + - pip install -qq flake8 + - flake8 + environment: + PY_COLORS: 1 + +trigger: + ref: + - refs/heads/main + - refs/tags/** + - refs/pull/** + +--- +kind: pipeline +name: testing-rocky9 + +platform: + os: linux + arch: amd64 + +concurrency: + limit: 1 + +workspace: + base: /drone/src + path: ${DRONE_REPO_NAME} + +steps: + - name: ansible-molecule + image: thegeeklab/molecule:3 + commands: + - molecule test -s rocky9 + environment: + HCLOUD_TOKEN: + from_secret: hcloud_token + +trigger: + ref: + - refs/heads/main + - refs/tags/** + - refs/pull/** + +depends_on: + - linting + +--- +kind: pipeline +name: documentation + +platform: + os: linux + arch: amd64 + +steps: + - name: generate + image: thegeeklab/ansible-doctor + environment: + ANSIBLE_DOCTOR_EXCLUDE_FILES: molecule/ + ANSIBLE_DOCTOR_FORCE_OVERWRITE: true + ANSIBLE_DOCTOR_LOG_LEVEL: INFO + ANSIBLE_DOCTOR_OUTPUT_DIR: _docs/ + ANSIBLE_DOCTOR_ROLE_NAME: ${DRONE_REPO_NAME#*.} + ANSIBLE_DOCTOR_TEMPLATE: hugo-book + + - name: publish + image: plugins/gh-pages + settings: + netrc_machine: gitea.rknet.org + pages_directory: _docs/ + password: + from_secret: gitea_token + remote_url: https://gitea.rknet.org/ansible/${DRONE_REPO_NAME} + target_branch: docs + username: + from_secret: gitea_username + when: + ref: + - refs/heads/main + +trigger: + ref: + - refs/heads/main + - refs/tags/** + - refs/pull/** + +depends_on: + - testing-rocky9 + +--- +kind: pipeline +name: notification + +platform: + os: linux + arch: amd64 + +clone: + disable: true + +steps: + - name: matrix + image: thegeeklab/drone-matrix + settings: + homeserver: + from_secret: matrix_homeserver + password: + from_secret: matrix_password + roomid: + from_secret: matrix_roomid + template: "Status: **{{ .Build.Status }}**
Build: [{{ .Repo.Owner }}/{{ .Repo.Name }}]({{ .Build.Link }}){{ if .Build.Branch }} ({{ .Build.Branch }}){{ end }} by {{ .Commit.Author }}
Message: {{ .Commit.Message.Title }}" + username: + from_secret: matrix_username + +trigger: + ref: + - refs/heads/main + - refs/tags/** + status: + - success + - failure + +depends_on: + - documentation + +--- +kind: signature +hmac: aaef009e2c8bb30a83837ba52368a718360a33d1628dca2b56bd200052296564 + +... diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d97b7cd --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# ---> Ansible +*.retry +plugins +library + +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + diff --git a/.later.yml b/.later.yml new file mode 100644 index 0000000..0efe5d5 --- /dev/null +++ b/.later.yml @@ -0,0 +1,19 @@ +--- +ansible: + custom_modules: + - iptables_raw + - openssl_pkcs12 + - proxmox_kvm + - ucr + - corenetworks_dns + - corenetworks_token + +rules: + exclude_files: + - molecule/ + - "LICENSE*" + - "**/*.md" + - "**/*.ini" + + exclude_filter: + - LINT0009 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..ef05acb --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +.drone* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fcac409 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Robert Kaussow + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1ffac0e --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# xoxys.vault + +[![Build Status](https://img.shields.io/drone/build/ansible/xoxys.vault?logo=drone&server=https%3A%2F%2Fdrone.rknet.org)](https://drone.rknet.org/ansible/xoxys.vault) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?label=license)](LICENSE) + +Setup HashiCorp Vaul secrets manager. You can find the full documentation at [https://galaxy.geekdocs.de](https://galaxy.geekdocs.de/roles/cloud/vault/). + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. diff --git a/defaults/main.yml b/defaults/main.yml new file mode 100644 index 0000000..230711e --- /dev/null +++ b/defaults/main.yml @@ -0,0 +1,73 @@ +--- +vault_version: latest +vault_image: "docker.io/hashicorp/vault:{{ vault_version }}" +# @var vault_url:description: > +# Specify address of the vault instance, used when building absolute urls, e.g. for websub. +# @end +vault_url: "http://localhost:8200" + +vault_restart_policy: always +vault_service_stopped: False + +vault_config_volume: "vault-config" +vault_data_volume: "vault-data" + +# @var vault_volumes:description: > Define required docker volumes. +# @end +# @var vault_volumes:example: > +# vault_volumes: +# - name: data +# # target location inside the container +# dest: /var/www/app/data +# type: volume +# @end +vault_volumes: + - name: "{{ vault_config_volume }}" + dest: /vault/config + - name: "{{ vault_data_volume }}" + dest: /vault/file + +# @var vault_network:description: > +# Name of the container network. If the name ends with `.network`, the network will be created with the specified configuration. +# Otherwise, the network must already exist and the container will be attached to the network. +# @end +vault_network: "vault.network" +vault_network_ipv6_enabled: False +# @var vault_network_ipv6_subnet:value: $ "_unset_" +# @var vault_network_ipv6_subnet:example: $ "fd00:0:0:2::/64" +# @var vault_network_ipv6_gateway:value: $ "_unset_" +# @var vault_network_ipv6_gateway:example: $ "fd00:0:0:2::1" + +# @var vault_network_ipv4_subnet:value: $ "_unset_" +# @var vault_network_ipv4_gateway:value: $ "_unset_" + +# @var vault_exposed_ports:description: > +# Ports you want to publish outside of Docker. Vault is running on `8200` inside of the container. +# @end +vault_exposed_ports: [] + +vault_cap_add: + - ipc_lock +vault_cap_drop: [] + +vault_podman_args: + - --pids-limit=-1 + - --userns=host + - --health-cmd='["wget", "--spider", "--proxy", "off", "http://localhost:8200/{{ __vault_health_path }}"]' + - --health-interval=5s + - --health-timeout=5s + - --health-retries=6 + - --health-on-failure=kill + +vault_default_user: "admin" +vault_default_password: "vault" + +vault_log_level: warn +vault_default_lease_ttl: 24h +vault_max_lease_ttl: 240h + +vault_ui: True +vault_disable_clustering: True + +vault_unseal_keys: [] +vault_auto_unseal: False diff --git a/handlers/main.yml b/handlers/main.yml new file mode 100644 index 0000000..fab79c1 --- /dev/null +++ b/handlers/main.yml @@ -0,0 +1,14 @@ +--- +- name: Restart vault + service: + name: vault + state: restarted + daemon_reload: True + listen: __vault_restart + +- name: Reload vault + service: + name: vault + state: reloaded + daemon_reload: True + listen: __vault_reload diff --git a/meta/main.yml b/meta/main.yml new file mode 100644 index 0000000..1e9c748 --- /dev/null +++ b/meta/main.yml @@ -0,0 +1,27 @@ +# Standards: 0.2 +--- +galaxy_info: + # @meta author:value: [Robert Kaussow](https://gitea.rknet.org/xoxys) + author: "Robert Kaussow " + namespace: xoxys + role_name: vault + # @meta description: > + # [![Source Code](https://img.shields.io/badge/gitea-source%20code-blue?logo=gitea&logoColor=white)](https://gitea.rknet.org/ansible/xoxys.vault) + # [![Build Status](https://img.shields.io/drone/build/ansible/xoxys.vault?logo=drone&server=https%3A%2F%2Fdrone.rknet.org)](https://drone.rknet.org/ansible/xoxys.vault) + # [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?label=license)](https://gitea.rknet.org/ansible/xoxys.vault/src/branch/main/LICENSE) + # + # Setup HashiCorp Vaul secrets manager. + # @end + description: Setup HashiCorp Vaul secrets manager + license: MIT + min_ansible_version: "2.10" + platforms: + - name: EL + versions: + - "9" + galaxy_tags: [] +dependencies: [] +collections: + - xoxys.general + - community.general + - containers.podman diff --git a/molecule/default b/molecule/default new file mode 120000 index 0000000..afa9fc6 --- /dev/null +++ b/molecule/default @@ -0,0 +1 @@ +rocky9 \ No newline at end of file diff --git a/molecule/pytest.ini b/molecule/pytest.ini new file mode 100644 index 0000000..c24fe5b --- /dev/null +++ b/molecule/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +filterwarnings = + ignore::DeprecationWarning diff --git a/molecule/requirements.yml b/molecule/requirements.yml new file mode 100644 index 0000000..927757f --- /dev/null +++ b/molecule/requirements.yml @@ -0,0 +1,12 @@ +--- +collections: + - name: https://gitea.rknet.org/ansible/xoxys.general + type: git + - name: community.general + - name: containers.podman + +roles: + - src: https://gitea.rknet.org/ansible/xoxys.podman + name: xoxys.podman + scm: git + version: main diff --git a/molecule/rocky9/converge.yml b/molecule/rocky9/converge.yml new file mode 100644 index 0000000..2fa4964 --- /dev/null +++ b/molecule/rocky9/converge.yml @@ -0,0 +1,9 @@ +--- +- name: Converge + hosts: all + roles: + - role: xoxys.podman + - role: xoxys.vault + vars: + vault_exposed_ports: + - 127.0.0.1:8200:8200 diff --git a/molecule/rocky9/create.yml b/molecule/rocky9/create.yml new file mode 100644 index 0000000..719600d --- /dev/null +++ b/molecule/rocky9/create.yml @@ -0,0 +1,120 @@ +--- +- name: Create + hosts: localhost + connection: local + gather_facts: false + no_log: "{{ molecule_no_log }}" + vars: + ssh_port: 22 + ssh_user: root + ssh_path: "{{ lookup('env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}/ssh_key" + tasks: + - name: Create SSH key + user: + name: "{{ lookup('env', 'USER') }}" + generate_ssh_key: true + ssh_key_file: "{{ ssh_path }}" + force: true + register: generated_ssh_key + + - name: Register the SSH key name + set_fact: + ssh_key_name: "molecule-generated-{{ 12345 | random | to_uuid }}" + + - name: Register SSH key for test instance(s) + hcloud_ssh_key: + name: "{{ ssh_key_name }}" + public_key: "{{ generated_ssh_key.ssh_public_key }}" + state: present + + - name: Create molecule instance(s) + hcloud_server: + name: "{{ item.name }}" + server_type: "{{ item.server_type }}" + ssh_keys: + - "{{ ssh_key_name }}" + image: "{{ item.image }}" + location: "{{ item.location | default(omit) }}" + datacenter: "{{ item.datacenter | default(omit) }}" + user_data: "{{ item.user_data | default(omit) }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: present + register: server + loop: "{{ molecule_yml.platforms }}" + async: 7200 + poll: 0 + + - name: Wait for instance(s) creation to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_jobs + until: hetzner_jobs.finished + retries: 300 + loop: "{{ server.results }}" + + - name: Create volume(s) + hcloud_volume: + name: "{{ item.name }}" + server: "{{ item.name }}" + location: "{{ item.location | default(omit) }}" + size: "{{ item.volume_size | default(10) }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: "present" + loop: "{{ molecule_yml.platforms }}" + when: item.volume | default(False) | bool + register: volumes + async: 7200 + poll: 0 + + - name: Wait for volume(s) creation to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_volumes + until: hetzner_volumes.finished + retries: 300 + when: volumes.changed + loop: "{{ volumes.results }}" + + # Mandatory configuration for Molecule to function. + + - name: Populate instance config dict + set_fact: + instance_conf_dict: + { + "instance": "{{ item.hcloud_server.name }}", + "ssh_key_name": "{{ ssh_key_name }}", + "address": "{{ item.hcloud_server.ipv4_address }}", + "user": "{{ ssh_user }}", + "port": "{{ ssh_port }}", + "identity_file": "{{ ssh_path }}", + "volume": "{{ item.item.item.volume | default(False) | bool }}", + } + loop: "{{ hetzner_jobs.results }}" + register: instance_config_dict + when: server.changed | bool + + - name: Convert instance config dict to a list + set_fact: + instance_conf: "{{ instance_config_dict.results | map(attribute='ansible_facts.instance_conf_dict') | list }}" + when: server.changed | bool + + - name: Dump instance config + copy: + content: | + # Molecule managed + + {{ instance_conf | to_nice_yaml(indent=2) }} + dest: "{{ molecule_instance_config }}" + when: server.changed | bool + + - name: Wait for SSH + wait_for: + port: "{{ ssh_port }}" + host: "{{ item.address }}" + search_regex: SSH + delay: 10 + loop: "{{ lookup('file', molecule_instance_config) | from_yaml }}" + + - name: Wait for VM to settle down + pause: + seconds: 30 \ No newline at end of file diff --git a/molecule/rocky9/destroy.yml b/molecule/rocky9/destroy.yml new file mode 100644 index 0000000..ed0b2ed --- /dev/null +++ b/molecule/rocky9/destroy.yml @@ -0,0 +1,78 @@ +--- +- name: Destroy + hosts: localhost + connection: local + gather_facts: false + no_log: "{{ molecule_no_log }}" + tasks: + - name: Check existing instance config file + stat: + path: "{{ molecule_instance_config }}" + register: cfg + + - name: Populate the instance config + set_fact: + instance_conf: "{{ (lookup('file', molecule_instance_config) | from_yaml) if cfg.stat.exists else [] }}" + + - name: Destroy molecule instance(s) + hcloud_server: + name: "{{ item.instance }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: absent + register: server + loop: "{{ instance_conf }}" + async: 7200 + poll: 0 + + - name: Wait for instance(s) deletion to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_jobs + until: hetzner_jobs.finished + retries: 300 + loop: "{{ server.results }}" + + - pause: + seconds: 5 + + - name: Destroy volume(s) + hcloud_volume: + name: "{{ item.instance }}" + server: "{{ item.instance }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: "absent" + register: volumes + loop: "{{ instance_conf }}" + when: item.volume | default(False) | bool + async: 7200 + poll: 0 + + - name: Wait for volume(s) deletion to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_volumes + until: hetzner_volumes.finished + retries: 300 + when: volumes.changed + loop: "{{ volumes.results }}" + + - name: Remove registered SSH key + hcloud_ssh_key: + name: "{{ instance_conf[0].ssh_key_name }}" + state: absent + when: (instance_conf | default([])) | length > 0 + + # Mandatory configuration for Molecule to function. + + - name: Populate instance config + set_fact: + instance_conf: {} + + - name: Dump instance config + copy: + content: | + # Molecule managed + + {{ instance_conf | to_nice_yaml(indent=2) }} + dest: "{{ molecule_instance_config }}" + when: server.changed | bool \ No newline at end of file diff --git a/molecule/rocky9/molecule.yml b/molecule/rocky9/molecule.yml new file mode 100644 index 0000000..675a389 --- /dev/null +++ b/molecule/rocky9/molecule.yml @@ -0,0 +1,24 @@ +--- +dependency: + name: galaxy + options: + role-file: molecule/requirements.yml + requirements-file: molecule/requirements.yml + env: + ANSIBLE_GALAXY_DISPLAY_PROGRESS: "false" +driver: + name: delegated +platforms: + - name: rocky9-vault + image: rocky-9 + server_type: cx11 +lint: | + /usr/local/bin/flake8 +provisioner: + name: ansible + env: + ANSIBLE_FILTER_PLUGINS: ${ANSIBLE_FILTER_PLUGINS:-./plugins/filter} + ANSIBLE_LIBRARY: ${ANSIBLE_LIBRARY:-./library} + log: False +verifier: + name: testinfra diff --git a/molecule/rocky9/prepare.yml b/molecule/rocky9/prepare.yml new file mode 100644 index 0000000..183f4d3 --- /dev/null +++ b/molecule/rocky9/prepare.yml @@ -0,0 +1,15 @@ +--- +- name: Prepare + hosts: all + gather_facts: false + tasks: + - name: Bootstrap python for Ansible + raw: | + command -v python3 python || ( + (test -e /usr/bin/dnf && sudo dnf install -y python3) || + (test -e /usr/bin/apt && (apt -y update && apt install -y python-minimal)) || + (test -e /usr/bin/yum && sudo yum -y -qq install python3) || + echo "Warning: Python not boostrapped due to unknown platform." + ) + become: true + changed_when: false diff --git a/molecule/rocky9/tests/test_default.py b/molecule/rocky9/tests/test_default.py new file mode 100644 index 0000000..cd05051 --- /dev/null +++ b/molecule/rocky9/tests/test_default.py @@ -0,0 +1,24 @@ +import os + +import testinfra.utils.ansible_runner + +testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( + os.environ["MOLECULE_INVENTORY_FILE"] +).get_hosts("all") + + +def test_vault_running_and_enabled(host): + vault = host.service("vault") + assert vault.is_running + assert vault.is_enabled + + +def test_vault_socket(host): + # Verify the socket is listening for HTTP traffic + assert host.socket("tcp://127.0.0.1:8200").is_listening + + +def test_vault_conn(host): + code = int(host.run("curl -s -w '%{http_code}' http://127.0.0.1:8200/v1/sys/health?standbyok=true -o /dev/null").stdout) # noqa + + assert code == 501 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..2bb8674 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,12 @@ +[flake8] +ignore = D100, D101, D102, D103, D105, D107, E402, W503 +max-line-length = 99 +inline-quotes = double +exclude = .git,.tox,__pycache__,build,dist,tests,*.pyc,*.egg-info,.cache,.eggs,env* + +[yapf] +based_on_style = google +column_limit = 99 +dedent_closing_brackets = true +coalesce_brackets = true +split_before_logical_operator = true diff --git a/tasks/main.yml b/tasks/main.yml new file mode 100644 index 0000000..bc0454e --- /dev/null +++ b/tasks/main.yml @@ -0,0 +1,86 @@ +--- +- block: + - name: Create network specs + template: + src: etc/containers/systemd/vault.network.j2 + dest: "/etc/containers/systemd/vault.network" + owner: root + group: root + mode: "0640" + when: vault_network | splitext | last == ".network" + notify: __vault_restart + + - name: Create container volumes + podman_volume: + name: "{{ item.name }}" + options: "{{ item.options | default(omit) }}" + state: "{{ item.state | default('present') }}" + loop: "{{ vault_volumes }}" + loop_control: + label: "{{ item.name }}" + when: item.type | default("volume") | lower == "volume" + register: __vault_volumes_raw + + - name: Register container volumes map + set_fact: + __vault_volumes_map: "{{ __vault_volumes_raw.results | json_query('[].volume') | items2dict(key_name='Name', value_name='Mountpoint') }}" + + - name: Deploy vault env file + template: + src: etc/containers/systemd/vault.env.j2 + dest: "/etc/containers/systemd/vault.env" + owner: root + group: root + mode: "0640" + notify: __vault_restart + + - name: Deploy vault config + template: + src: vault/config.hcl.j2 + dest: "{{ __vault_volumes_map[vault_config_volume] }}/config.hcl" + owner: root + group: root + mode: "0644" + notify: __vault_reload + + - name: Create container specs + template: + src: etc/containers/systemd/vault.container.j2 + dest: "/etc/containers/systemd/vault.container" + owner: root + group: root + mode: "0640" + notify: __vault_restart + + - name: Ensure service state + systemd: + name: "vault.service" + state: started + daemon_reload: True + enabled: True + become: True + become_user: root + +- block: + - name: Flush handlers + meta: flush_handlers + + - name: Wait for Vault startup + uri: + url: "{{ vault_url }}/{{ __vault_health_path }}" + follow_redirects: none + method: GET + register: __vault_http_result + until: __vault_http_result.status == 200 + retries: 10 + delay: 3 + + - name: Unseal vault + hashivault_unseal: + keys: "{{ vault_unseal_keys }}" + url: "{{ vault_url }}" + become: True + become_user: root + when: + - vault_auto_unseal | bool + - vault_unseal_keys | length > 0 diff --git a/templates/etc/containers/systemd/vault.container.j2 b/templates/etc/containers/systemd/vault.container.j2 new file mode 100644 index 0000000..2f14049 --- /dev/null +++ b/templates/etc/containers/systemd/vault.container.j2 @@ -0,0 +1,34 @@ +#jinja2: lstrip_blocks: True +{{ ansible_managed | comment }} +[Install] +WantedBy=default.target + +[Service] +Restart=on-failure +RestartSec=5s + +ExecReload=/usr/bin/podman kill --signal=SIGHUP {{ __vault_container_name }} + +[Container] +Image={{ vault_image }} +ContainerName={{ __vault_container_name }} +Exec=/usr/local/bin/docker-entrypoint.sh server +EnvironmentFile=/etc/containers/systemd/vault.env +{% for item in vault_volumes %} +Volume={{ item.name }}:{{ item.dest }}:Z +{% endfor %} + +{% if vault_cap_add | length > 0 %} +AddCapability={{ vault_cap_add | join(" ") }} +{% endif %} +{% if vault_cap_drop | length > 0 %} +DropCapability={{ vault_cap_drop | join(" ") }} +{% endif %} + +Network={{ vault_network }} +{% for item in vault_exposed_ports %} +PublishPort={{ item }} +{% endfor %} +{% for item in vault_podman_args %} +PodmanArgs={{ item }} +{% endfor %} diff --git a/templates/etc/containers/systemd/vault.env.j2 b/templates/etc/containers/systemd/vault.env.j2 new file mode 100644 index 0000000..4686925 --- /dev/null +++ b/templates/etc/containers/systemd/vault.env.j2 @@ -0,0 +1,3 @@ +#jinja2: lstrip_blocks: True +{{ ansible_managed | comment }} +VAULT_ADDR={{ vault_url }} diff --git a/templates/etc/containers/systemd/vault.network.j2 b/templates/etc/containers/systemd/vault.network.j2 new file mode 100644 index 0000000..eb8f0a8 --- /dev/null +++ b/templates/etc/containers/systemd/vault.network.j2 @@ -0,0 +1,19 @@ +#jinja2: lstrip_blocks: True +{{ ansible_managed | comment }} +[Network] +{% if vault_network_ipv4_subnet is defined %} +Subnet={{ vault_network_ipv4_subnet }} +{% endif %} +{% if vault_network_ipv4_gateway is defined %} +Gateway={{ vault_network_ipv4_gateway }} +{% endif %} +IPv6={{ vault_network_ipv6_enabled | bool | lower }} +{% if vault_network_ipv6_enabled | bool %} +{% if vault_network_ipv6_subnet is defined %} +Subnet={{ vault_network_ipv6_subnet }} +{% endif %} +{% if vault_network_ipv6_gateway is defined %} +Gateway={{ vault_network_ipv6_gateway }} +{% endif %} +{% endif %} +Label=app=vault diff --git a/templates/vault/config.hcl.j2 b/templates/vault/config.hcl.j2 new file mode 100644 index 0000000..46f1074 --- /dev/null +++ b/templates/vault/config.hcl.j2 @@ -0,0 +1,21 @@ +ui = {{ vault_ui | bool | lower }} +api_addr = "{{ vault_url }}" +disable_clustering = {{ vault_disable_clustering | bool | lower }} +log_level = "{{ vault_log_level }}" + +default_lease_ttl = "{{ vault_default_lease_ttl }}" +max_lease_ttl = "{{ vault_max_lease_ttl }}" + +storage "file" { + path = "/vault/file" +} + +listener "tcp" { + address = "[::]:8200" + tls_disable = true +} + +telemetry { + prometheus_retention_time = "1m" + disable_hostname = true +} diff --git a/vars/main.yml b/vars/main.yml new file mode 100644 index 0000000..1fccd5c --- /dev/null +++ b/vars/main.yml @@ -0,0 +1,3 @@ +--- +__vault_container_name: vault-server +__vault_health_path: v1/sys/health?standbyok=true&uninitcode=200