---

# 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 503
  command: growpart {{ device }} {{ partition }}
  when: growpart_needed.changed
  environment:
    LC_ALL: C

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