Variables And Templates In Ansible
Last Updated :
21 Mar, 2024
Let’s say you are owning a small technological company and you need to get the machines set up in a way that it’s correct and as it should be. This might have you installing core software packages, copying over and tweaking system config files or getting involved in system settings just to name a few of the many things you have to do. Now, you may choose to do this all by manual as you may do it one by one for each individual server, but are you willing to sacrifice your time or be patient enough to do such a mind-boggling task? Healthcare or nursing education can be truly hard work!
And at this stage the thing called Ansible is a technical powerhouse that comes to rescue here. In other words, Ansible allows you to automate your boring setup tasks by writing playbooks, which are just files containing some custom-written command-lines and other instructions. Playbacks are similar to cookbook, the only difference is that in the book the ingredients and the steps to make the good recipe are listed but you're providing your servers team with step-by-step instructions of what you want them to do.
What Is Ansible?
Ansible playbooks are like small packets of instructions where the playbooks themselves are notifying Ansible to execute on one or more servers or devices. They are written in YAML syntax, which is YAML syntax was created to be a simple and human-readable data format. The playbook can include one or a combination of plays. Every play specifies a set of hosts that are the servers/A devices in which the tasks within a particular play should be carried out. For example, a hacker can concentrate on web servers. However, the next hacker may pursue another target, that is, database servers.
Every play internally features tasks, which basically is the set of those specific actions or operations you expect Ansible to run on your hosts. Day-to-day tasks include packages installation, creating/editing files and folders, operation of the services (starting and stopping), and command or script execution, files copying mostly.
The main operations are absent, which are available in Ansible modules. Users can use those modules for management or working with services like web servers.

A Step-By-Step Guide On Writing Playbook With Variables And Templates In Ansible
Step 1: Installing Ansible
- To start writing the playbooks, first of all install Ansible on a control machine you have. In your case, it will either be your local machine or a server that you keep consecrated.
- Ensure there is a directory that will be responsible for the storage of your playbooks.
- The installation of Ansible can be carried out by running the command for the latest release from the official page of Ansible. Installing Ansible
Step 2: Set Up The Inventory File
The name this new file is to be known as is inventory and you will add the IP addresses or hostnames of the target machines you want to use to execute the playbook. For example:
[webservers]
203.0.113.10

Step 2: Create A Variables File
- Variables in Ansible have a wide area of definition, regardless of whether they are directly in the playbook, or are defined in separate files.
- We can have variables alone on one file apart. Create a new file called vars.yml with the following content:
http_port: 8080
max_clients: 200

Step 3: Create a Template File
- Schemas provide a way of generating configuration files dynamically under the wave of variables.
- Create a new file called httpd.conf.j2 with the following
# This is the main Apache HTTP server configuration file.
#
Listen {{ http_port }}
MaxClients {{ max_clients }}
# ... other configuration options ...

- The following screenshot illustrates on defining the template file.

Step 4: Create The Playbook
- Now, create a new file called apache.yml for your Ansible playbook:
---
- hosts: webservers
vars_files:
- vars.yml
tasks:
- name: Install Apache
yum:
name: httpd
state: present
- name: Configure Apache
template:
src: httpd.conf.j2
dest: /etc/httpd/conf/httpd.conf
notify:
- restart apache
handlers:
- name: restart apache
service:
name: httpd
state: restarted
In this playbook:
- hosts indicates destinations for the tasks, i.e. webservers to be executed.
- vars_files is the namespace with the parent directory docs with the file vars.yml in it containing the variables as they are.
- tasks is a list of tasks to be executed on the target hosts:tasks is a list of tasks to be executed on the target hosts:
- The first job uses the yum module to bring the package Apache.
- As the next stage, the template module copies the httpd.conf.j2 template to the server-side destination /etc/httpd/conf/httpd.conf and the httpd.conf file on the destination hosts. This command line repo also tells the restart apache handler as soon as a change is observed.
- handlers, in particular, encapsulate an action of the Apache service restart when the Configure Apache task provides real time feedback.

Step 5: Execute The Playbook
- Run the Ansible playbook using the ansible-playbook command:
ansible-playbook -i inventory apache.yml
- This command will execute the tasks defined in the apache.yml playbook on the hosts specified in the inventory file.

Step 6: Verify The Results
- This is done immediately after implementing the playbook, when you can see the edited state of the target devices.
- For instance, checking the /etc/httpd/conf/httpd.conf for the updated Apache configuration file on the target hosts is recommended so that the directives such as Listen and MaxClients, which have the values from the vars.yml file put in, are updated accordingly.

- Finally, by referring to these steps, you have created and implemented an Ansible playbook which may access information by names defined in vars.yml file and apache’s configuration file made of the template called httpd.conf.j2.
Advantages Of Variables And Templates In Ansible
The following are the advantages of Variables In Ansible:
- Reusability: The benefit of variables is the fact that you can only define the values once and use them repeatedly throughout Ansible, thus eliminating the need to write the same thing over and over again.
- Centralized Management: You can deposit the variables (e.g., from a central location such as variable files, inventories or roles) and access them via multiple playbooks and task where it can help you to keep it updated and managed easily.
- Consistency: When you use variables, each time you want to have a particular value, you do not use the coding manually instead, you have rest assured that all the block codes you have use the same or consistent value.
- Flexibility: You can store different types of information using variables, for example, a text strings, a number, a list, or a dictionary thus giving you an opportunity to represent a complex configuration.
Advantages Of Templates In Ansible
The following are the advantages of templates in Ansible:
- Dynamic File Generation: Templates enable you to make a new file (such as configuration file and installation script) by replacing placeholders with the variable values that is relevant to the case, hence you don’t need to do the editing manually.
- Reusability: Non-duplicated code could be reused via a given template to generate multiple files for various servers or environments, thus reducing the duplicated code.
- Readability: Templates split the content that will not change, leaving just the dynamic parts in the config files, which makes the later more readable and straight forward.
- Separation Of Concerns: The templates tend to be their key to separating the construction philosophy (how the file should be structured) and the configurable values (variable values) in favor of structural and structured programming.
Disadvantages Of Variables And Templates In Ansible
The following are the disadvantages of Variable in Ansible:
- Complexity: As the number of variables increases, studying and understanding their interconnections and the dependencies among many will likely get more complicated, especially when these occur in a large-scale setting.
- Scope Issues: In the procedure, a variable may have different scopes (e.g., a global level or a play level or a host level or a task level) and misunderstanding the rule of the variable precedence can lead to the result which is not expected or to a conflict.
- Security Concerns: Any sensitive data such as passwords or API keys stored in plaintext variables makes the system prone to hacking once the codes are available publicly.
- Debugging Challenges: Often time when an error is attributable to an unpredictable variable, tracking its origin can be a problem.
Disadvantages Of Templates In Ansible
- Learning Curve: Even though templates are efficient, the template commonsense and logic often stay to learn and in fact it can be even difficult for complex iterations that include conditional statements and loops.
- Performance Overhead: Inherence of templates independently comes with the added overhead of performance which gets rampant especially when there is a complex or large set of templates to display or to generate a large number of files.
- Debugging Complexity: Troubleshooting within templates is a challenge at times since the result after rendering may be different from the source code whereas in another case, it is much easier to find and rectify twists and corners in the path of least resistance.
- Dependency Management: The use of templates with references to other data source files or variables defined in other files may lead to a more sophisticated difficulty of dependency management later on.
- Version control challenges: Template itself may be version controlled, but monitoring the differences of the rendered output files, especially the files containing binary contents and the large configuration sets may be more complicated.
Therefore, it is critical to carefully evaluate the disadvantages of employing of variables and templates and consider if the advantages outweigh these disadvantages in Ansible. The strategic planning, document organization and observing best practices help to weed out some the challenges and deliver a seamless and well-oiled Ansible system.
Conclusion
Although Ansible offers a set of variables (that influence the general operations) and templates (those are similar to Google Docs), their effect on the management of infrastructure can be considered as a strong point of such tool. By harnessing variables, you can consolidate and reuse configuration data, define consistency, as well as separate concerns accordingly to enable a more modular and maintainable Ansible code. While forms help you make editable files that can be tailored to meet different requirements by adjusting property values, templates facilitate the creation of dynamic files that can be customized by various customer input, thus reducing time consumption and encouraging code reuse. However, they are not without their downside as they can be complex to implement, having security issues to be dealt with, for debugging to be done and the overhead of performance to be managed. Though, the challenges of getting the job done properly in many cases can be alleviated once there is appropriate planning, documentation and adherence to the best practices.
Similar Reads
Understanding Templates Variable in Angular
Template variables in Angular allow us to use the data from one part of the template to another part of the same template. There are various use cases where these template variables come in handy. For example, responding to the user input or responding to the form submission. In this article, we'll
4 min read
<%= vs <%- in EJS Template Engine
EJS (Embedded JavaScript) is a popular templating engine that helps generate dynamic HTML content using JavaScript. It allows embedding JavaScript logic into HTML, making it a powerful tool for rendering server-side content in Node.js applications.In this article, weâll compare <%= %> and <
4 min read
GitLab CI/CD Variables
GitLab CI/CD variables allow you to customize your CI/CD pipelines by defining and managing key values used in the build, deployment, and operational processes. These variables act as placeholders for dynamic data, such as environment-specific settings, sensitive information like passwords, or any o
4 min read
How to use variables and data files together in Postman ?
In this article, we are going to learn the process of using variables and data files together in the Postman. Postman is a powerful tool for API testing, offering extensive capabilities for automating tests and handling various API request types. One of its key features is the ability to use variabl
6 min read
What are templates in AngularJS ?
Templates in AngularJS are simply HTML files filled or enriched with AngularJS stuff like attributes and directives. A directive is a marker element that is used to target a particular attribute or class to render its behavior according to the needs. Model and controller in Angular are combined with
3 min read
Ansible and Jinja2: Creating Dynamic Templates
Automation is a very integral part of modern IT operations, where teams can deploy, manage, and scale applications in quite an easy manner. Ansible, with its agentless architecture and very easy configuration language, is one powerful automation tool to do these tasks. One of the most versatile feat
7 min read
How to print a variable directly using EJS template engine?
EJS (Embedded JavaScript) is a templating engine for NodeJS that enables dynamic content generation in web applications. To print a variable directly in an EJS template, you can use the <%= variable %> syntax. This syntax allows you to embed and display the value of a variable directly within
2 min read
Difference between views and templateUrl in AngularJS
In this article, we will see what is Views and TemplateUrl in AngularJS, along with understanding their basic usage through the code snippets & finally see some differences between them. A Views is anything that a user sees on a screen and is used to set up multiple views or to target views manu
4 min read
Overview of Ansible Inventories
Ansible can be referred to as an open-source automation platform accustomed to configuration and application management as well as task automation. In the context of mapping the powerful capabilities of Ansible, inventories are at the core that specifies the target systems to work on. This article o
7 min read
Creating Templates with Ansible Template Module
Ansible is indeed powerful IT automation software; in its excellent functionalities, the template module stands out with the functionality to apply dynamic generation of configuration files. This is an essential functionality as one of the challenges in managing environments is the fact that differe
7 min read