---
- name: "Creating some hcloud volumes for backup purpose"
  hcloud_volume:
    api_token: "{{ hetzner_authentication_ansible }}" 
    name: "postgres-backup--{{ inventory_hostname }}--vol{{ item }}"
    server: "{{ inventory_hostname }}"
    labels:
      stage: "{{ stage }}"
      used_for: "{{ inventory_hostname }}"
    size: 10
    state: present
    delete_protection: yes
  loop: "{{ range(1,2) | list }}"
  register: created_volume
  delegate_to: localhost
  become: false

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

- name: "Setting LVM related VARs"
  set_fact:
    pvs: "{{ hcloud_volumes_found.hcloud_volume_info | json_query(jmesquery) }}"
    vg_name: vg.postgres_backup
    lv_name: lv.postgres_backup
  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%FREE'
  when:
  - create_vg.changed

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

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