I’d like to set a common_apt_packages
list based on OS distribution, so I’ve used jinja2 if condition as the script below, but the return common_apt_packages
type is AnsibleUnsafeText
- hosts: localhost
vars:
common_apt_packages_ubuntu_22_04:
- ack-grep
- acl
- apt-transport-https
- build-essential
- dstat
- git-core
- htop
- iftop
- iotop
tasks:
- name: Set common_apt_packages for ubuntu {{ ansible_distribution_version }}
set_fact:
common_apt_packages: "{% if ansible_distribution_version =='22.04' %} {{ common_apt_packages_ubuntu_22_04 }} {% else %} {{ common_apt_packages_ubuntu_18_04 }} {% endif %}"
How can I improve the script to return common_apt_packages
as a List variable?
2
Answers
Just remove the white spaces between
%} {{
and}} {%
, because Ansible will then handle it as a string, not as a list.With
type_debug
you can get the output type.When you try to install them using the apt module:
Create the lists. For example in group_vars
and put the lists of the packages into a dictionary. For example,
gives (abridged)
Your problem is that output of Jinja is always a string. Ansible should convert it automatically if it is a valid YAML. If you for whatever reason have to use Jinja create the string first and convert it to YAML explicitly. For example,
You can’t put the declarations into a single set_fact because the second declaration knows nothing about the first one. But, you can put them into any vars, of course.
Test of the conversion in Ansible 2.12.9 Python 3.8.5, and Jinja 3.0.1
gives (abridged)