ansible-playbook-lab-excercise-part-3

Create a playbook where you should install a webserver into 2 OS type(Ubuntu and RHEL) with fact conditioning. and list out a directory which in “/etc” and display such as “This is a directory /file in /etc:-XXXx”
To be used Conditiong, looping, regiter and fact variable.

---
- name: Update web servers
  hosts: web
   
  tasks:
  - name: Install the latest version of Apache on RedHat
    yum:
      name=httpd
      state=latest
    when: ansible_os_family == "RedHat"
  - name: Install the latest version of Apache on Debian
    apt:
      name=apache2
      state=latest
    when: ansible_os_family == "Debian"
  - name: Copy file with owner and permissions
    ansible.builtin.copy:
      src: index.html
      dest: /var/www/html/index.html
  - name: Start service httpd, if not started
    ansible.builtin.service:
      name=httpd
      state=started
   - name: List all files and directories in /etc
      shell: ls /etc
      register: dir_contents
    - name: Print directory contents using loops
      debug:
        msg: "This is a directory /file in /etc : {{ item }}"
      loop: "{{ dir_contents.stdout_lines }}"

There are 2 environment DEV and QA. Both has their own group_vars. Using it, in Dev and QA environment(RHEL/CENTOS) install apache and Dev should run with 80 port and QA should run with 8080 port. Whereas config file location for apache conf is /etc/httpd/conf/httpd.conf and line for port is “Listen 80”. This should be done using template module and zinja2 lib.

#inventory
[dev]
a.a.a.a

[qa]
b.b.b.b
#group_vars/dev
portnum = 80
#group_vars/qa
portnum = 8080
#httpd.conf.j2
...
listen {{ portnum }}
---
- name: Update web servers
  hosts: all
	
  tasks:
  - name: Install the latest version of Apache on centos
    yum:
      name=httpd
      state=latest
  - name: Start service httpd, if not started
    ansible.builtin.service:
      name=httpd
      state=started
  - name: Template a file to /etc/file.conf
    ansible.builtin.template:
      src: httpd.conf.j2
      dest: /etc/httpd/conf/httpd.conf
	  notify:
      - Start service httpd, if not started

  handlers:
  - name: Start service httpd, if not started
    ansible.builtin.service:
      name=httpd
      state=restarted

Write a 3 yaml playbook i.e main.yaml, second.yaml and third.yaml with some demo debug tasks and call second.yaml and third.yaml from main.yaml using inlcude.

#second.yaml
---
- name: Update web servers
  hosts: web
  vars:
    - name: "second"
   
  tasks:
  - name: Print the vars
    ansible.builtin.debug:
      msg: this is {{ name }} yaml file
#third.yaml
---
- name: Update web servers
  hosts: web
  vars:
    - name: "third"
   
  tasks:
  - name: Print the vars
    ansible.builtin.debug:
      msg: this is {{ name }} yaml file
#main.yaml
---
- name: Update web servers
  hosts: web

   
  tasks:
  - name: include second yaml
    include: second.yaml
  - name: include third yaml
    include: third.yaml