Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ansible: use of loop var to index a data structure

I try to loop over a list of structured objects like:

users:
  - user_name: frank
    user_fullname: Andrew U. Frank
  - user_name: frank
    user_fullname: Andrew U. Frank

but the loop does return immediately (not seeing any of the list):

- name: process the users 
  debug: 
    msg: 
       - item "{{item}}"
  loop:  "{{users}}"

If I include the processing with a file, then it seems to work to produce output

- name: process the users 
  include_tasks: process_user.yml
  loop:  "{{users}}"

file: process_user.yml:

- name: start process_user
  debug: 
    msg: 
      - item "{{item}}"
      - user_name1 "{{item.user_name}}"

Why does the same code included with a file work, but not when next to the loop?

It produces the correct info and I can use "{{ item.user_name }}" in other tasks, immediate problem resolved (but without undertanding why?)

The structure I would prefer would be:

users:
  - user_frank:
      user_name: frank
      user_fullname: Andrew U. Frank
  - user_andrew:
      user_name: andrew
      user_fullname: andrew

so I could form loops over an arbitrary list of such users, but I cannot see how to construct the loop:

loop: 
    - "{{users[user_frank]}}"
    - "{{users[user_andrew]}}"

gives list object has no element AnsibleUndefined. Is this not the same as above? i.e. a list of structures with two dict entries (user_name and user_fullname)?

I have read and re-read the chapter in my ansible book and the online documentation, but I must admit that I do not understand how to use variables.

Can anybody help? pointers to documentation etc. are much appreciated!

question from:https://stackoverflow.com/questions/65848824/ansible-use-of-loop-var-to-index-a-data-structure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...