how to create Ansible playbook to obtain OS versions of the remote hosts?

Use one of the following Jinja2 expressions:

{{ hostvars[inventory_hostname].ansible_distribution }}
{{ hostvars[inventory_hostname].ansible_distribution_major_version }}
{{ hostvars[inventory_hostname].ansible_distribution_version }}

where:

  • hostvars and ansible_... are built-in and automatically collected by Ansible
  • ansible_distribution is the host being processed by Ansible

For example, assuming you are running the Ansible role test_role against the host host.example.com running a CentOS 7 distribution:

---
- debug:
    msg: "{{ hostvars[inventory_hostname].ansible_distribution }}"
- debug:
    msg: "{{ hostvars[inventory_hostname].ansible_distribution_major_version }}"
- debug:
    msg: "{{ hostvars[inventory_hostname].ansible_distribution_version }}"

will give you:

TASK [test_role : debug] *******************************************************
ok: [host.example.com] => {
    "msg": "CentOS"
}

TASK [test_role : debug] *******************************************************
ok: [host.example.com] => {
    "msg": "7"
}

TASK [test_role : debug] *******************************************************
ok: [host.example.com] => {
    "msg": "7.5.1804"
}

In a structured way:

- hosts: all
  become: no
  vars:
    output_file: os.csv
  tasks:
    - block:
        # For permisison setup.
        - name: get current user
          command: whoami
          register: whoami
          run_once: yes

        - name: clean file
          copy:
            dest: "{{ output_file }}"
            content: 'hostname,distribution,version,release'
            owner: "{{ whoami.stdout }}"
          run_once: yes

        - name: fill os information
          lineinfile:
            path: "{{ output_file }}"
            line: "{{ ansible_hostname }},\
              {{ ansible_distribution }},\
              {{ ansible_distribution_version }},\
              {{ ansible_distribution_release }}"
          # Tries to prevent concurrent writes.
          throttle: 1
      delegate_to: localhost

Creates a comma separated file named os.csv in execution folder. You can use any variables you want editing line:.