---
- name: Config system network,like hostname,interface name and ip address etc.
  hosts: myInitHosts
  become: true

# This is my defined vars,include hostname and other
  vars_files:
    - 00_myvars_config.yml

  tasks:
  - name: Check if network device name is already updated
    shell: 'cat /etc/default/grub | grep -E "^\s*GRUB_CMDLINE_LINUX.*net.ifnames=0.*$"'
    register: grub_output
    ignore_errors: true

  - name: Backup /etc/default/grub
    copy:
      src: /etc/default/grub
      dest: /etc/default/grub.bak
    when: grub_output.rc == 1

  - name: Update kernel grub command line arguments
    replace:
      path: /etc/default/grub
      regexp: '^GRUB_CMDLINE_LINUX="'
      replace: 'GRUB_CMDLINE_LINUX="net.ifnames=0 biosdevname=0 '
    register: grub_config
    when: grub_output.rc == 1

  - name: Loading grub config
    command: grub2-mkconfig -o /boot/grub2/grub.cfg
    when: grub_config is succeeded

  - name: Reboot the system
    shell: "sleep 10 && /sbin/reboot"
    async: 0
    poll: 0
    ignore_unreachable: yes

  - name: Wait 30 seconds
    pause:
      seconds: 30

  - name: Config host name
    command: hostnamectl set-hostname "{{ hostname }}"

  - name: Delete old network config file
    file:
      path: /etc/sysconfig/network-scripts/ifcfg-e*
      state: absent

  - name: Configure IP address
    nmcli:
      ifname: "{{ ifname }}"
      conn_name: "{{ conn_name }}"
      type: ethernet
      state: present
      mtu: 1500
      autoconnect: True
      ip4: "{{ ip_address }}/{{ netmask }}"
      gw4: "{{ gateway }}"
      dns4: "{{ dns_servers }}"
    ignore_errors: true
    async: 10
    poll: 0

#  - name: debug
#    debug:
#      var: grub_config
  
#  handlers:
#      ignore_errors: true
#    - name: restart network
#      systemd:
#        name: NetworkManager
#        state: restarted
    
#    - name: active network
#      command: nmcli connection up "{{ conn_name }}"
