简体   繁体   中英

How to read a complex include variables in Ansible

I have a variable file that has multiple variables "name" & "path" listing under an IP address like below.

10.0.0.12
    - name: exe_folder
      path: /tmp/exe
    - name: log_folder
      path: /tmp/log
    - name: src_folder
      path: /tmp/src

10.0.0.13
    - name: test_folder
      path: /tmp/exe1
    - name: out_folder
      path: /tmp/log1
    - name: com_folder
      path: /tmp/src1

 etc ....

I can loop on the name and path successfully in my playbook as below.

   - name: Load repository
     include_vars:
       file="{{ playbook_dir }}/vars/list.yml"
       name=user1

   - debug:
       msg: "{{ item.name + ':' + item.path }}"  
     loop: "{{ user1[inventory_hostname] }}"  

   - set_fact:
       allinonecmd: "{{ allinonecmd | default('') + 'ls -ltr ' + item.path + ' '}}"  
     loop: "{{ user1[inventory_hostname] }}"  

My requirement is to have a new variable "mycode" under each IP however just have a single mention of it and I should be able to print it in the loop like above playbook does.

Thus i need my variable file to have mycode specified onetime for each IP. I'm not sure what changes I need to make to my variable file and playbook to accomodate this requirement.

10.0.0.12
    - name: exe_folder
      path: /tmp/exe
      mycode: "56.12"
    - name: log_folder
      path: /tmp/log
    - name: src_folder
      path: /tmp/src

10.0.0.13
    - name: test_folder
      path: /tmp/exe1
      mycode: "76.88"
    - name: out_folder
      path: /tmp/log1
    - name: com_folder
      path: /tmp/src1

 etc ....

The playbook fails after I make the above changes and try to print the mycode variable.

   - debug:
       msg: "{{ item.name + ':' + item.path + item.mycode }}"  
     loop: "{{ user1[inventory_hostname] }}"  

Error Output:

fatal: [10.0.0.12]: FAILED! => {
    "msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'mycode'

Note: I do not wish to specify mycode multiple times under an IP as it looks like a dirty solution.

I think that for this use case, you can use default() filter, so if this element is not on the list, you can recall a default one or omit it.

vars:
  my_default_value: "56.12"

   - debug:
       msg: "{{ item.name + ':' + item.path + (item.mycode | default(my_default_value) }}"       loop: "{{ user1[inventory_hostname] }}"  

Even you can make a combination with default(value) and default(omit) to fit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM