---

# Running growpart seems to be only required on Azure, as other Cloud Providers do this at boot time

- name: Install growpart
  package:
    name: cloud-utils-growpart
    state: present

- name: Gather mounts facts
  setup:
    gather_subset: 'mounts'

- name: Search root filesystem device
  vars:
    query: "[?mount=='/'].device"
    _root_device: "{{ ansible_mounts | json_query(query) }}"
  set_fact:
    device: "{{ _root_device | first | regex_replace('([^0-9]+)[0-9]+', '\\1') }}"
    partition: "{{ _root_device | first | regex_replace('[^0-9]+([0-9]+)', '\\1') }}"
    root_device: "{{ _root_device }}"

- name: Check if growpart needs to be run
  command: growpart -N {{ device }} {{ partition }}
  failed_when: False
  changed_when: "'NOCHANGE:' not in growpart_needed.stdout"
  register: growpart_needed
  environment:
    LC_ALL: C

- name: Check fs type
  command: file -Ls {{ root_device }}
  changed_when: False
  register: fs_type

- name: Run growpart  # noqa no-handler
  command: growpart {{ device }} {{ partition }}
  when: growpart_needed.changed
  environment:
    LC_ALL: C

- name: Run xfs_growfs  # noqa no-handler
  command: xfs_growfs {{ root_device }}
  when: growpart_needed.changed and 'XFS' in fs_type.stdout
