Search code examples
ansible

Ansible | lookup with variable inside loop


I would like to get specific dict based on ansible_distribution variable and use it inside with_items but I can't retrive dict content using lookup. I try something like this:

- hosts: all
  gather_facts: true
  become: yes
  vars:
    distributions:
      Centos: 
        repos:
          - repo_name: 'repo1'
            baseurl: 'url1' 
            file: 'file1'
            gpgkey: 'gpgkey1'
      Rocky:
        repos:
          - repo_name: 'repo2'
            baseurl: 'url2' 
            file: 'file2
            gpgkey: 'gpgkey2'
  
  tasks:   
    - name: Add Yum Repo
      become: yes
      yum_repository:
        name: "{{ item.repo_name }}"
        description: EpelUpdate
        baseurl: "{{ item.baseurl }}"
        file: " {{ item.file }}"
        gpgcheck: 0
        gpgkey: "{{ item.gpgkey }}"
      with_items:
        - "{{ lookup(vars, distributions.{{ ansible_distribution }}.repos) }}" #<-- this line is wrong

I get error: "msg": "template error while templating string: expected name or number. String: {{ lookup(vars, distributions.{{ ansible_distribution }}.repos) }}"


Solution

  • I found solution. Simple "{{ distributions[ansible_distribution].repos }}" is enough