skip to Main Content

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
...

3

Answers


  1. 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) }}
    

    Source: https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#when-should-i-use-also-how-to-interpolate-variables-or-dynamic-variable-names

    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] }}"
    
    Login or Signup to reply.
  2. 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) }}"
    
    Login or Signup to reply.
  3. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search