Part 10 – Using Jinja Variables

Think of Jinja2 as variables inside text files.

eg: Welcome to {{ inventory_hostname }} and Ansible turns it to Welcome to centos01 and that’s about it

Jinja lives in:

roles/baseline/templates/motd.j2

This is pure Jinja2 variables

  • {{ inventory_hostname }} → the VM name
  • {{ ansible_distribution }} → Ubuntu / CentOS
  • {{ ansible_kernel }} → kernel version
  • {{ ansible_default_ipv4.address }} → primary IP
Welcome to {{ inventory_hostname }}.
Managed by Ansible Baseline Role.

Environment: {{ motd_environment }}
Owner: {{ motd_owner }}

OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
Kernel: {{ ansible_kernel }}
IP: {{ ansible_default_ipv4.address }}

This file contains TASKS that has an existing motd file so we will replace that will jinja

roles/baseline/tasks/main.yml

Ansible will read motd.j2 config below . In the last exercise we had motd configured like this so we just replace this pointing to a variable called jinja.

– name: Set custom MOTD
copy:
dest: /etc/motd
content: |
Welcome to this server.
Managed by Ansible Baseline Role.
Unauthorized access is prohibited.

- name: Baseline role is running
  debug:
    msg: "Baseline tasks executed"

- name: Set system timezone
  timezone:
    name: "Europe/London"

- name: Update package cache
  package:
    update_cache: yes

- name: Upgrade all packages to latest
  package:
    name: "*"
    state: latest

- name: Install baseline packages
  package:
    name: "{{ packages }}"
    state: present

- name: Remove unwanted packages
  package:
    name: "{{ unwanted_packages }}"
    state: absent

- name: Deploy MOTD template as Jinja
  template:
    src: motd.j2
    dest: /etc/motd
    owner: root
    group: root
    mode: '0644'

- name: Ensure SSH service is running
  service:
    name: sshd
    state: started
    enabled: true
  
- name: Ensure SSH service is running
  service:
    name: "{{ ssh_service }}"
    state: started
    enabled: true

This file contains VARIABLES and here we add a motd

roles/baseline/vars/main.yml
packages:
  - curl
  - wget
  - vim
  - git
  - htop
  - lsof
  - tcpdump
  - traceroute
  - unzip
  - tar
  - gzip
  - jq
  - rsync
  - tree
  - socat
  - bash-completion
  - psmisc
  - open-vm-tools
  - openssh-server
ssh_service: "{{ 'sshd' if ansible_distribution == 'CentOS' else 'ssh' }}"

unwanted_packages:
  - telnet
  - ftp
  - rsh
  - talk
  - ypbind

motd_environment: "LAB"
motd_owner: "VMAnalyst"

Define the playbook under

/etc/ansible/playbooks/baseline-init.yml 
---
- hosts: all
  become: true
  roles:
    - baseline

Do a dry run

Run the playbook

Login and check

(Visited 8 times, 1 visits today)

By Ash Thomas

Ash Thomas is a seasoned IT professional with extensive experience as a technical expert, complemented by a keen interest in blockchain technology.