---
- name: Install iSCSI storage plugin dependencies
  package:
    name: "{{ pkg_list | join(',') }}"
    state: present
  register: result
  until: result is succeeded
  vars:
    pkg_list:
      - iscsi-initiator-utils
      - device-mapper-multipath

- name: restart services
  systemd:
    name: "{{ item }}"
    state: started
    enabled: True
  with_items:
    - multipathd
    - rpcbind
    - iscsid

# Copy the conf file only if not exists
- name: Template multipath configuration
  template:
    dest: "/etc/multipath.conf"
    src: multipath.conf.j2
    backup: true
    force: no

# check whether devices section is present
- name: Check devices section present
  command: grep -e "^devices {" /etc/multipath.conf
  register: devices_multipath
  failed_when: false

# Add empty devices section if not present
- name: "Add devices section"
  blockinfile:
    path: /etc/multipath.conf
    marker: "# <!-- {mark} ANSIBLE MANAGED BLOCK -->"
    block: |
      devices {
      }
    owner: root
    group: root
    mode: 0600
    backup: yes
    state: present
  when: devices_multipath.rc == 1

# Update LIO section under devices section
- name: "Add LIO-ORG in MultiPath configuration"
  blockinfile:
    path: /etc/multipath.conf
    insertafter: "devices {"
    marker: "# <!-- {mark} ANSIBLE MANAGED BLOCK - LIO iSCSI device -->"
    block: |
          device {
                    vendor "LIO-ORG"
                    product "TCMU device"
                    user_friendly_names "yes"
                    path_grouping_policy "failover"
                    path_selector "round-robin 0"
                    failback immediate
                    path_checker "tur"
                    prio "alua"
                    hardware_handler "1 alua"
                    no_path_retry 120
                    rr_weight "uniform"
          }
    owner: root
    group: root
    mode: 0600
    backup: yes
    state: present

#enable multipath
- name: Enable and start multipath
  command: "mpathconf --enable --with_multipathd y"
