How to prepare Ansible inventory, playbook and configuration file used by Ansible module using Ansible/Jinja2?

Hi,

I have a plain-text file “routers” in versioning system which contains host-names separated by newlines:

$ cat routers
r1
r2
r3
$

I also have routers configuration templates in versioning system as a plain-text files. For example:

$ cat system:syslog
system {
syslog {
host 10.10.10.153 {
any notice;
daemon info;
}
}
}
$

I can’t change the format of those two types of files because they are used by other systems. Now what I need, is to create Ansible inventory file from this “routers” file, configuration file for Ansible junos_config(https://docs.ansible.com/ansible/junos_config_module.html) module from routers configuration template and finally Ansible playbook in YAML. At the moment I use a bash script for this. Simplified, it takes four arguments:

  1. “routers” file
  2. configuration template file(for example “system:syslog” described above)
  3. ticket number in ticketing system(integer)
  4. comment string(this is used in router to describe the change)

Based on the example above, “routers” file is converted to inventory file with following content:

junipers ansible_connection=local
[junipers]
r1
r2
r3

“system:syslog” file is converted to a file name “<ticket_nr>.cfg” with following content:

groups {
replace: system:syslog {
system {
syslog {
host 10.10.10.153 {
any notice;
daemon info;
}
}
}
}
}

Basically, bash script does something like this:

cat << EOF
groups {
replace: ${templatefile##*/} {
EOF
sed ‘s/^/ /’ “$templatefile”
cat << EOF
}
}
EOF

And finally playbook file is generated:

  • hosts: junipers
    remote_user: admin
    tasks:
  • name: Change routers conf.
    ignore_errors: yes
    junos_config:
    comment: “”
    timeout: 60
    port: 22
    src: <ticket_nr>.cfg
    src_format: text
    replace: yes

“” and “<ticket_nr>” are arguments given to the bash script. In addition, this bash script checks out the latest revision of mentioned “routers” file and configuration template.

Now is there a better way to do all this without bash? While this works, I’m feeling that I’m doing it wrong and I’m relying heavily on bash. Is it possible to do all this in Ansible/Jinja2?

thanks,
Martin