In this lab, participants will familiarize themselves with how Ansible uses the template
module to deploy configuration files on servers. The lab emphasizes the importance of separating configuration data from tasks, allowing for dynamic content generation.
- Learn to use the
template
module for configuration file deployment. - Understand how to use Jinja2 templates for dynamic value substitution.
- Create reusable playbooks for consistent configurations.
- Ansible installed on the participant's machine.
- A basic understanding of Ansible playbooks and templates.
- A target host or set of hosts categorized as
webservers
in your Ansible inventory. - A template file named
config.ini.jn2
in your working directory.
Estimated Time: 20 minutes
-
Create a new playbook named
config_deployment_demo.yml
. -
Define the play structure:
--- - name: Deploy Configuration Files Using Templates hosts: webservers gather_facts: no
-
Add variables for database configuration under the
vars
section:vars: dbUsername: root dbPassword: mySecurePassword
-
Ensure you have a template file named
config.ini.jn2
in your working directory. -
Add the following content to the template file:
db_username = {{ dbUsername }} db_pass = {{ dbPassword }}
Explanation:
{{ dbUsername }}
and{{ dbPassword }}
use Jinja2 syntax to dynamically substitute values from the playbook variables.
-
Add a task to deploy the configuration file using the
template
module:tasks: - name: Deploy the configuration file template: src: config.ini.jn2 dest: ~/config.ini
Explanation:
src
: Specifies the source template file.dest
: Specifies the destination path on the target server.
-
Save the
config_deployment_demo.yml
file. -
Run the playbook using the following command:
ansible-playbook config_deployment_demo.yml
-
Observe the output to ensure the configuration file is successfully deployed to the target servers.
You can compare your playbook with the config_deployment_demo.yml file in the current directory.
This lab demonstrated how to use Ansible's template
module to deploy dynamic configuration files. By utilizing templates, you can maintain consistent configurations across environments while allowing for dynamic substitutions. Mastering this technique is essential for creating scalable and adaptable automation workflows. 👏