Ansible Playbook Lab & Excercise – Part 3
Limited Time Offer!
For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!
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: Assignment 2
hosts: localhost
vars:
webserver: httpd
tasks:
- name: Install the latest version of webserver
yum:
name={{ webserver}}
state=latest
when: ansible_os_family == "RedHat"
- name: Install the latest version of webserver
apt:
name={{ webserver}}
state=latest
when: ansible_os_family == "Ubuntu"
- name: Install the latest version of webserver
apt:
name={{ webserver}}
state=latest
when: ansible_os_family == "Ubuntu"
- name: Return motd to registered var
ansible.builtin.command: ls /etc
register: find_output
- debug:
msg: "The list in directory /etc is" {{ find_output.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 locaton for apache conf is /etc/httpd.conf/conf/httpd.conf and line for port is “Listen 80”. This should be done using template module and zinja2 lib.
#group_vars/dev
port: 80
#group_vars/qa
port: 8080
---
- name: Template module and zinza2 module
hosts: dev,qa
tasks:
- name: Install latest httpd
yum:
name: httpd
state: latest
- 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
- name: Start service httpd, if not started
ansible.builtin.service:
name=httpd
state=started
- debug:
msg: Port {{ port }}
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 include.
# second.yaml
- name: Debug
debug:
msg: In second.yaml
# third.yaml
- name: Debug
debug:
msg: In third.yaml
#main.yaml
- hosts: all
tasks:
- debug:
msg: task1
- include: second.yaml
- include: third.yaml