Deploying File Templates on Remote Hosts
Once you have created your Ansible file templates, you can deploy them to remote hosts using the template
module. Here's how you can do it:
Deploying a Single File Template
To deploy a single file template, you can use the following Ansible task:
- name: Deploy Nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/conf.d/default.conf
notify:
- restart nginx
In this example, the template
module is used to deploy the nginx.conf.j2
template file to the /etc/nginx/conf.d/default.conf
location on the remote hosts. The notify
section triggers a handler to restart the Nginx service after the configuration file is deployed.
Deploying Multiple File Templates
If you need to deploy multiple file templates, you can use a loop in your Ansible playbook:
- name: Deploy configuration files
template:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
loop:
- { src: "nginx.conf.j2", dest: "/etc/nginx/conf.d/default.conf" }
- { src: "app.conf.j2", dest: "/etc/app/app.conf" }
notify:
- restart nginx
- restart app
In this example, the template
module is used to deploy two configuration files, nginx.conf.j2
and app.conf.j2
, to their respective destinations on the remote hosts. The loop
section allows you to specify multiple file templates to be deployed.
After the configuration files are deployed, the notify
section triggers handlers to restart the Nginx and application services.
Handling Sensitive Data
If your file templates contain sensitive data, such as database credentials or API keys, you can use Ansible Vault to securely store and deploy this information. Ansible Vault allows you to encrypt your sensitive data, ensuring that it is not stored in plain text in your playbooks or templates.
By following these best practices for deploying Ansible file templates, you can streamline your infrastructure management and ensure consistency across your remote hosts.