Managing Jinja2 Templates Using Ansible Kodekloud


Question: One of the Nautilus DevOps team members is working on to develop a role for httpd installation and configuration. Work is almost completed, however there is a requirement to add a jinja2 template for index.html file. Additionally, the relevant task needs to be added inside the role. The inventory file ~/ansible/inventory is already present on jump host that can be used. Complete the task as per details mentioned below:

a. Update ~/ansible/playbook.yml playbook to run the httpd role on App Server 2.

b. Create a jinja2 template index.html.j2 under /home/thor/ansible/role/httpd/templates/ directory and add a line This file was created using Ansible on <respective server> (for example This file was created using Ansible on stapp01 in case of App Server 1). Also please make sure not to hard code the server name inside the template. Instead, use inventory_hostname variable to fetch the correct value.

c. Add a task inside /home/thor/ansible/role/httpd/tasks/main.yml to copy this template on App Server 2 under /var/www/html/index.html. Also make sure that /var/www/html/index.html file's permissions are 0655.

d. The user/group owner of /var/www/html/index.html file must be respective sudo user of the server (for example tony in case of stapp01).

Note: Validation will try to run the playbook using command ansible-playbook -i inventory playbook.yml so please make sure the playbook works this way without passing any extra arguments.


Go to ansible folder

Edit the playbook.yml file according to question

- hosts: stapp02
  become: yes
  become_user: root
    - role/httpd    

 Then go to templates folder and create index.html.j2

 This file was created using Ansible on {{ ansible_hostname }}

 Finally edit the main.yml file on tasks folder

- name: install the latest version of HTTPD
    name: httpd
    state: latest

- name: Start service httpd
    name: httpd
    state: started
- name: Use Jinja2 template to generate index.html
    src: /home/thor/ansible/role/httpd/templates/index.html.j2
    dest: /var/www/html/index.html
    mode: "0655"
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"

Then go to ansible folder and run the command

ansible-playbook  -i inventory playbook.yml

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment


Post a Comment