AnsibleRookie
AnsibleRookie

Reputation: 1

ANSIBLE: Is there a way to assign a value to nested dynamic variables in vars file?

I'm tyring to use the find module to find file patterns with variables from an external vars file that has dynamic variables in a list of dictionaries. How can I assign values to those dynamic variables in vars file while accessing them from the playbook?

deletememes.yml:

---
  name: generic name
  hosts: all
  vars_files: vars.yml
  tasks:
   - set_fact: 
      combinedlist: "{{ first_list + second_list }}"

   - find: 
      paths: "{{ item.0.path }}" # pass a value(item.1.username?) here for the username in the vars file  
          patterns: "{{ item.0.extension }}" 
        register: someRegister
        with_items:
         - combinedlist
         - usernameList # for the value in 

vars.yml

---
    first_list:
     - { path : "/Users/{{ username }}/memes/" , extension : '{{ username }}_*.jpg'}
     - { path : "/someOtherFolder/{{ username }}/catVideos/" , extension : '{{ item.username }}_*.mp4'}  

    second_list:
     - { path : "/{{ memesrc }}/memes/" , extension : '{{ memesrc }}_*.gif'}

ERROR:

"msg": "The task includes an option with an undefined variable. The error was: 'username' is undefined\n\nThe error appears to have been in 'deletememes.yml'

Upvotes: 0

Views: 1044

Answers (1)

Jack
Jack

Reputation: 6168

Vars files are not dynamic. You would have to make those assignments in set_fact tasks. Now, you have to break up the variable from the text and use the string concatination operator, +. I'm only showing one list here:

---
- hosts: localhost
  connection: local

  vars:
    external_list_of_users:
      - username: fred
      - username: barney
      - username: wilma
      - username: betty

  tasks:
  - name: Create arrays
    set_fact:
      first_list: []

  - name: Put items in arrays
    set_fact:
      first_list: "{{ first_list + [ { 'path' : '/Users/'+item.username+'/memes/' , 'extension' : item.username+'_*.jpg' } ] }}"
    with_items:  "{{ external_list_of_users }}"

  - name: Show vars
    debug:
      var: first_list

The result of that last task is:

TASK [Show vars] *******************************************************************************************
ok: [localhost] => {
    "first_list": [
        {
            "extension": "fred_*.jpg", 
            "path": "/Users/fred/memes/"
        }, 
        {
            "extension": "barney_*.jpg", 
            "path": "/Users/barney/memes/"
        }, 
        {
            "extension": "wilma_*.jpg", 
            "path": "/Users/wilma/memes/"
        }, 
        {
            "extension": "betty_*.jpg", 
            "path": "/Users/betty/memes/"
        }
    ]
}

Upvotes: 1

Related Questions