###
# This Playbook contains validations which run for every region. 
# Input: {{ item }} - is the combination of region name and ip in the format
#                     <region_name>:<region_ip>
#                     Example: westus:10.0.0.2
# The region gets configured at the start of the playbook and rest of the
# playbook runs all the validations which are dependent on the region.
# For example - yum calls
###

---
- name: Set image properties
  set_fact:
    region_name: "{{ item.split(':')[0] }}"
    region_ip: "{{ item.split(':')[1] }}"
    out_folder: /tmp/out
    err_folder: /tmp/err
    yum_out_file: yumrepolist_out.log
    yum_err_file: yumrepolist_err.log

- name: Set /etc/hosts for a region
  copy:
    dest: "/etc/hosts"
    content: |
      127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
      ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
      {{ region_ip }}   rhui-1.microsoft.com rhui-2.microsoft.com rhui-3.microsoft.com rhui4-1.microsoft.com

- name: Clean logs from pevious run
  shell: |
    rm -rf {{out_folder}}/{{ region_name}}
    rm -rf {{err_folder}}/{{ region_name}}

- name: Create yum err directory
  file:
    path: "{{ out_folder }}/{{ region_name}}"
    state: directory

- name: Create yum err directory
  file:
    path: "{{ err_folder }}/{{ region_name}}"
    state: directory

- name: Create err and out files
  file:
    path: "{{ file_name }}"
    state: touch
  with_items: 
    - "{{err_folder}}/{{region_name}}/{{ yum_err_file }}"
    - "{{out_folder}}/{{region_name}}/{{ yum_out_file }}"
  loop_control:
    loop_var: file_name

- name: Run Yum Repolist
  shell: |
    yum update -q -y --disablerepo='*' --enablerepo='*microsoft-azure*'

    yum clean all
    yum repolist -v
  register: yum_output
  ignore_errors: yes

- name: Write to error file if repolist failed
  copy:
    dest: "{{err_folder}}/{{region_name}}/{{ yum_err_file }}"
    content: "{{yum_output.stderr}} {{yum_output.stdout}}"
  when: yum_output.rc != 0

- name: Write to error msg if repolist failed
  lineinfile:
    path: "{{err_folder}}/err_msgs.log"
    line: "Yum repolist failed for {{region_name}}"
    create: yes
    state: present
  when: yum_output.rc != 0

- name: Write to output file if repolist succeded
  copy:
    dest: "{{out_folder}}/{{region_name}}/{{ yum_out_file }}"
    content: "{{yum_output.stderr}} {{yum_output.stdout}}"
  when: yum_output.rc == 0