---
- name: Add the Vault group
  ansible.builtin.group:
    name: vault
    state: present
    gid: 997

- name: Add the Vault system account
  ansible.builtin.user:
    name: vault
    comment: " Hashicorp Vault User"
    state: present
    system: true
    group: vault
    uid: 998

- name: Create directory for Hashicorp's GPG key
  ansible.builtin.file:
    path: /etc/apt/keyrings
    state: directory
    mode: '0755'

- name: Add Hashicorp's official GPG key
  ansible.builtin.apt_key:
    url: https://apt.releases.hashicorp.com/gpg
    keyring: /etc/apt/keyrings/hashicorp.gpg
    state: present

- name: Print architecture variables
  ansible.builtin.debug:
    msg: "Architecture: {{ ansible_architecture }}, Codename: {{ ansible_lsb.codename }}"

- name: Add Hashicorp repository
  ansible.builtin.apt_repository:
    repo: >-
      deb [arch={{ arch_mapping[ansible_architecture] | default(ansible_architecture) }}
      signed-by=/etc/apt/keyrings/hashicorp.gpg]
      https://apt.releases.hashicorp.com {{ ansible_lsb.codename }} main
    filename: hashicorp
    state: present

- name: Install Hashicorp Vault
  ansible.builtin.apt:
    name: "{{ item }}"
    state: present
    update_cache: true
  loop:
    - vault

- name: Include certificates.yml task
  ansible.builtin.include_tasks: certificates.yml

- name: Create directory for Vault's data
  ansible.builtin.file:
    path: /opt/vault/data
    state: directory
    owner: vault
    group: vault
    mode: '0755'

- name: Create directory for Vault's raft data
  ansible.builtin.file:
    path: /opt/vault/raft
    state: directory
    owner: vault
    group: vault
    mode: '0755'

- name: Template vault.hcl file
  ansible.builtin.template:
    src: vault.hcl.j2
    dest: /etc/vault.d/vault.hcl
    owner: vault
    group: vault
    mode: '0640'

- name: Enable and start Vault services
  ansible.builtin.systemd:
    name: "{{ item }}"
    enabled: true
    state: started
  loop:
    - vault.service

- name: Open port for vault on the host firewall {{ item }}
  ansible.builtin.iptables:
    chain: INPUT
    protocol: tcp
    destination_port: "{{ item }}"
    jump: ACCEPT
    comment: Accept Vault connections.
  loop:
    - "{{ vault_port }}"
    - "{{ vault_cluster_port }}"
