Ansible is very flexible configuration management tool and offers wide range of options to perform certain tasks. I am very often use Jinja2 template option to complete the following tasks.
- Create configuration files using extra variables
- Create email templates based on playbook results.
- Prepare Terraform TF files.
Template Config files:
1. Let’s create a new playbook to update /etc/hosts file using template.
--- - hosts: all become: yes tasks: - name: Template the /etc/hosts file based on user variables. template: src: /var/tmp/hosts.j2 dest: /var/tmp/hosts
2. Prepare the new template for /etc/hosts
# cat /var/tmp/hosts.j2 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 {{IPADDRESS}} {{HOSTNAME}}
3. Execute the playbook to write the new host files on defined location. (for testing , i had give the path name as /var/tmp)
# ansible-playbook -i temp_inv2 update_hosts.yaml -e IPADDRESS=192.168.3.56 -e HOSTNAME=uxtst001 PLAY [all] ************************************************************************* TASK [Gathering Facts] ************************************************************************* ok: [localhost] TASK [Template the /etc/hosts file based on user variables.] ************************************************************************* changed: [localhost] PLAY RECAP ************************************************************************* localhost : ok=2 changed=1 unreachable=0 failed=0
4. Verify the new passed variables in the configuration file.
cat /var/tmp/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.3.56 uxtst001
Using jinja2 template option, we have successfully updated passed hostname and IP address in the file at given location. To more information about the template module, please checkout ansible documentation – Ansible Template – File-out on Remote server
Leave a Reply