Ansible新手求助:with_items循环中register变量被覆盖问题解决
Hey there! Let's work through this variable override issue you're hitting with your Ansible Playbook.
The Root of the Problem
You're trying to dynamically name registered variables with expiration_date_{{item}}, but that's not how Ansible handles loop registrations. Every iteration of your with_items loop is overwriting the same variable (even with the dynamic name), so by the end of the first task, you only have the expiration date for the last user in your list. Ansible is designed to store all loop results in a single registered variable as a list of result objects, not as separate dynamically named variables.
The Solution: Use a Single Registered Variable
Instead of trying to create unique variables per user, register all expiration date results into one variable. Ansible will automatically populate a results list inside this variable, where each entry corresponds to a user in your with_items list—each entry even includes the original item (username) so you can map results back to users.
Here's your revised Playbook:
--- - hosts: all become: true tasks: - name: Check accounts expiration dates shell: "chage -l {{ item }} | grep 'Account expires' | cut -d':' -f2" args: warn: no register: user_expiration_results with_items: - user1 - user2 - user3 - name: Extend expiration date for users with May 31 expiration user: name: "{{ item.item }}" # Access the original username from the result entry expires: 1540944000 when: "'May 31' in item.stdout" loop: "{{ user_expiration_results.results }}"
Breakdown of the Changes:
- Single Registered Variable: We now register all results to
user_expiration_results. Theresultsattribute of this variable holds an array where each element contains:item: The original username from yourwith_itemsliststdout: The output of yourchagecommand for that user
- Loop Through Results: The second task loops over
user_expiration_results.resultsinstead of reusing the original user list. This lets us directly access each user's expiration date and username from the same result object. - Condition Check: The
whenclause now usesitem.stdoutto check if the expiration date contains "May 31", anditem.itemgives us the username to update.
This approach avoids variable overrides entirely and aligns with how Ansible is intended to handle looped task results.
内容的提问来源于stack exchange,提问作者Paddyc

