---
- name: "Creating some hcloud volumes for LVM purpose"
  hcloud_volume:
    api_token: "{{ hetzner_authentication_ansible }}"
    name: "{{ lvm_with_hetzner_volumes__volprefix }}-{{ inventory_hostname }}--vol{{ item }}"
    server: "{{ inventory_hostname }}"
    labels:
      stage: "{{ stage }}"
      used_for: "{{ lvm_with_hetzner_volumes__volprefix }}"
      bound_on: "{{ inventory_hostname }}"
      vol_no: "{{ item | string }}"
    size: "{{ lvm_with_hetzner_volumes__volsize }}"
    state: present
    delete_protection: yes
  loop: "{{ range(1, lvm_with_hetzner_volumes__volcount+1) | list }}"
  register: created_volume
  delegate_to: localhost
  become: false

- name: "Getting all hcloud volumes for {{ inventory_hostname }}"
  hcloud_volume_info:
    api_token: "{{ hetzner_authentication_ansible }}"
    label_selector: "stage={{ stage }},used_for={{ lvm_with_hetzner_volumes__volprefix }},bound_on={{ inventory_hostname }}"
  register: hcloud_volumes_found
  delegate_to: localhost
  become: false

- name: "Getting all hcloud volumes for {{ inventory_hostname }}"
  debug:
    msg: "{{ hcloud_volumes_found }}"

- name: "Setting LVM related VARs"
  set_fact:
    pvs: "{{ hcloud_volumes_found.hcloud_volume_info | json_query(jmesquery) }}"
    vg_name: "vg.{{ lvm_with_hetzner_volumes__volprefix }}"
    lv_name: "lv.{{ lvm_with_hetzner_volumes__volprefix }}"
  vars:
    jmesquery: "[*].linux_device"

- name: "Creating a volume group on top of all found hcloud volumes"
  community.general.lvg:
    vg: "{{ vg_name }}"
    pvs: "{{ pvs }}"
    pvresize: yes
  register: create_vg

- name: "Create logical volume" # noqa no-handler
  community.general.lvol:
    vg: "{{ vg_name }}"
    lv: "{{ lv_name }}" 
    size: '100%PVS'
  when:
    - create_vg.changed

- name: "Format volume"
  filesystem:
    fstype: ext4
    dev: "/dev/{{ vg_name }}/{{ lv_name }}"

- name: "Resize volume" # noqa no-handler
  filesystem:
    fstype: ext4
    dev: "/dev/{{ vg_name }}/{{ lv_name }}"
    resizefs: yes
  when:
    - create_vg.changed

# set noqa linter 'tag' due to unknown file permissions/ownership for mount path ;
# must be set in role etc in which this role will be called!!!
- name: "Ensure mountpath exists without setting permission/ownership" # noqa risky-file-permissions
  file:
    path: "{{ lvm_with_hetzner_volumes__mountpath }}"
    state: directory

- name: "Mount created LVM volume"
  mount:
    path: "{{ lvm_with_hetzner_volumes__mountpath }}"
    src: "/dev/{{ vg_name }}/{{ lv_name }}"
    fstype: ext4
    state: mounted
