- name: Install Python3 OpenSSL
  ansible.builtin.apt:
    name: python3-openssl
    state: present

- name: Ensure group Certs exists
  ansible.builtin.group:
    state: present
    system: true
    name: "certs"

- name: Set permissions to group
  ansible.builtin.file:
    path: /etc/vault.d/ssl
    owner: vault
    group: vault
    mode: '0750'
    state: directory

- name: Create Private key (RSA, 4096 bits)
  community.crypto.openssl_privatekey:
    path: /etc/vault.d/ssl/{{ inventory_hostname }}.key
  # run_once: true

- name: Set ownership of certificate key file
  ansible.builtin.file:
    path: /etc/ssl/private/private.key
    owner: "vault"
    group: "vault"
    mode: "0640"

- name: Create certificate signing request (CSR) for self-signed certificate
  community.crypto.openssl_csr_pipe:
    privatekey_path: /etc/vault.d/ssl/{{ inventory_hostname }}.key
    common_name: "{{ inventory_hostname }}.{{ vault_domain_name }}"
    organization_name: "We Build Your Cloud B.V."
    subject_alt_name:
      - "DNS:localhost"
      - "DNS:{{ inventory_hostname }}"
      - "DNS:{{ inventory_hostname }}.{{ vault_domain_name }}"
      - "IP:{{ ansible_default_ipv4.address }}"
      - "IP:127.0.0.1"
    extended_key_usage:
      - serverAuth
  # run_once: true
  register: csr

- name: Sign certificate with our CA
  community.crypto.x509_certificate_pipe:
    csr_content: "{{ csr.csr }}"
    provider: ownca
    ownca_path: /Users/pderuiter/ca/ca-certificate.crt
    ownca_privatekey_path: /Users/pderuiter/ca/ca-certificate.key
    ownca_privatekey_passphrase: "{{ secret_ca_passphrase }}"
    ownca_not_after: +720d
    ownca_not_before: "-1d"
  delegate_to: localhost
  # run_once: true
  register: certificate
  become: false

- name: Write certificate to file on target server
  ansible.builtin.copy:
    dest: /etc/vault.d/ssl/{{ inventory_hostname }}.crt
    content: "{{ certificate.certificate }}"
    owner: "vault"
    group: "vault"
    mode: "0640"
  # run_once: true

- name: Copy CA certificate to target system
  ansible.builtin.copy:
    src: /Users/pderuiter/ca/ca-certificate.crt
    dest: /etc/vault.d/ssl/ca-wbyc-certificate.pem
    owner: "vault"
    group: "vault"
    mode: "0640"
