PawelN
PawelN

Reputation: 33

Ansible - dynamic variable with host_vars and string in the name

I'm trying to create a job role in Ansible to run yum install/update of packages, which will be provided by a 3rd party system as a .yml file to vars directory in a role with following convention: server01.yml, server02.yml, serverX.yml with variable in form packageList_serverNumber: 'list of packages'. This variable will be read using a task:

 - name: server update packages from host_vars
yum:
  name: "{{ install_pkgs }}"
  state: latest

This should point to host_vars file for specific host:

install_pkgs: "{{ packageList_server01 }}"

As this task should only run when the variable is defined, I was trying to use when clause with variable which will point to packageList_serverNumber. When I hardcode it, like below it is working:

when: packageList_server01 is defined

Can you please advise how to make it dynamic? I was trying with:

when: packageList_{{hostvars[inventory_hostname]}} is defined

But unfortunately this is not working.

Upvotes: 3

Views: 592

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Use lookup plugin vars. Run the command below to see the details

shell> ansible-doc -t lookup vars

Given the vars files

shell> cat roles/test4/vars/server01.yml 
packageList_server01: [pkg1, pkg2, pkg3]

shell> cat roles/test4/vars/server02.yml 
packageList_server02: [pkg4, pkg5, pkg6]

shell> cat roles/test4/vars/server03.yml 
packageList_server03: [pkg7, pkg8, pkg9]

read the vars, declare the variable install_pkgs, and use it

shell> cat roles/test4/tasks/main.yml
- include_vars: "vars/{{ inventory_hostname }}.yml"
- set_fact:
    install_pkgs: "{{ lookup('vars', 'packageList_' ~ inventory_hostname) }}"
- debug:
    msg: "Install {{ install_pkgs }}"

For example the playbook

- hosts: server01,server02,server03
  gather_facts: false
  roles:
    - test4

gives (abridged)

TASK [test4 : debug] ****
ok: [server01] => 
  msg: Install ['pkg1', 'pkg2', 'pkg3']
ok: [server03] => 
  msg: Install ['pkg7', 'pkg8', 'pkg9']
ok: [server02] => 
  msg: Install ['pkg4', 'pkg5', 'pkg6']

Upvotes: 1

Related Questions