Skip to main content

Working with Ansible Templates, Variables, and Facts

Hands-On Lab


Photo of Stosh Oldham

Stosh Oldham

Course Development Director in Content





Besides being an objective on the Red Hat Certified Ansible Specialist Exam, a demonstrated ability to use Ansible templates, variables, and facts is essential to practical systems deployment through Ansible. Templates allow for a streamlined approach to configuration management that reduces configuration error and simplifies system upkeep. This learning activity starts a student on a path from basic Ansible knowledge to a strong working knowledge that is necessary for real-world application.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Working with Ansible Templates, Variables, and Facts

The Scenario

A colleague was the unfortunate victim of a scam email, and their network account was compromised. Shortly after we finished helping them pack up their desk, our boss gave us the assignment to promote system security by deploying a hardened sudoers file. We need to create an Ansible template of the sudoers file.

We also need to create an accompanying playbook in /home/ansible/security.yml that will deploy this template to all servers in the default inventory.

Important notes:

  • Ansible has been installed on the control node.
  • The user ansible has been already created on all servers with the appropriate shared keys for access to the necessary servers from the control node. It has the same password as cloud_user.
  • All necessary Ansible inventories have already been created.

Logging In

Log into the control node (control1) as the ansible user, using login credentials on the hands-on lab overview page.

Create a Template sudoers File

[ansible@control1]$ vim /home/ansible/hardened.j2

Now that we're in Vim, we'll put these contents in the file:

%sysops {{ ansible_default_ipv4.address }} = (ALL) ALL
Host_Alias WEBSERVERS = {{ groups['web']|join(' ') }}
Host_Alias DBSERVERS = {{ groups['database']|join(' ') }}
%httpd WEBSERVERS = /bin/su - webuser
%dba DBSERVERS = /bin/su - dbuser

Create a Playbook

[ansible@control1]$ vim /home/ansible/security.yml

The security.yml file should look like this:

 - hosts: all
   become: yes
   - name: deploy sudo template
       src: /home/ansible/hardened.j2
       dest: /etc/sudoers.d/hardened
       validate: /sbin/visudo -cf %s

Run the Playbook

[ansible@control1]$ ansible-playbook /home/ansible/security.yml

The output will show that everything deployed fine, but we can check locally to make sure. Let's become root (with sudo su -) and then read our file:

[root@control1]$ cat /etc/sudoers.d/hardened

The custom IP and host aliases are in there.


Congratulations on completing the lab!