Reputation: 3
I would like to install Apache on several linux server. Apache package has not the same name on RedHat or Debian operating system (apache2 vs httpd): Is it a way to use an ansible fact variable ("ansible_os_family") as a key of a dictionary variable ?
Something like that (but this doesn't work) :
---
- name: playbook1
hosts: all
become: yes
vars:
apache_packages: {
"RedHat": "httpd",
"Debian": "apache2"
}
tasks:
- name: Install Apache server
package:
name: "{{ apache_packages['{{ ansible_os_family }}'] }}"
state: present
...
Upvotes: 0
Views: 426
Reputation: 226
I would do some thing like below to reduce the lines
- hosts: localhost
become: yes
tasks:
- package:
name: "{{ 'apache2' if ansible_os_family == 'Debian' else ('httpd' if ansible_os_family == 'RedHat') }}"
state: present
Upvotes: 0
Reputation: 897
try this: you define packages as a dict of list (based on os family)
- name: playbook1
hosts: localhost
become: yes
vars:
packages:
debian:
- apache2
redhat:
- httpd
tasks:
- name: Install Apache server
package:
name: "{{ item }}"
state: present
loop: "{{ packages.get(ansible_os_family|lower) }}"
Upvotes: 0
Reputation: 39099
Nesting Jinja delimiters inside another Jinja delimiter is never a good idea.
Another rule is ‘moustaches don’t stack’. We often see this:
{{ somevar_{{other_var}} }}
The above DOES NOT WORK as you expect, if you need to use a dynamic variable use the following as appropriate:
{{ hostvars[inventory_hostname]['somevar_' + other_var] }}
For ‘non host vars’ you can use the vars lookup plugin:
{{ lookup('vars', 'somevar_' + other_var) }}
If you don't surround something with quotes, it will be assumed as being a variable, so in this case, this is as simple as:
name: "{{ apache_packages[ansible_os_family] }}"
Upvotes: 1