You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible新手求助:with_items循环中register变量被覆盖问题解决

Fixing Ansible Variable Override in Loop-Based Registration

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:

  1. Single Registered Variable: We now register all results to user_expiration_results. The results attribute of this variable holds an array where each element contains:
    • item: The original username from your with_items list
    • stdout: The output of your chage command for that user
  2. Loop Through Results: The second task loops over user_expiration_results.results instead of reusing the original user list. This lets us directly access each user's expiration date and username from the same result object.
  3. Condition Check: The when clause now uses item.stdout to check if the expiration date contains "May 31", and item.item gives 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:32:50