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

Ansible如何通过set_fact依据文件存在条件定义新用户列表

问题场景

我已经获取了系统所有用户的列表{{ users }},希望检查这些用户的主目录中是否存在指定文件,随后定义包含满足文件存在条件的用户的新列表。现有以下Ansible任务片段:

- name: Get all users in system
  shell: |
    cat /etc/passwd | awk -F':' '{ print $1}'
  register: users

- set_fact:
    all_users: "{{ users.stdout_lines | list  }}"

- name: Check if file exists 
  file:
    path: /home/{{ item }}/指定文件名  # 需替换为实际要检查的文件名
    state: file
  register: file_status
  loop: "{{ all_users }}"

- set_fact:
    new_user_list: "get users from all_users that meet the previous conditions of file exist"

还有一段错误的set_fact尝试:

- set_fact:
    new_user_list:  {{ all_users }}
    when: file_status.exist

请问如何正确使用set_fact实现该需求?


正确实现方式

因为file模块配合loop执行后,注册的变量会是一个包含所有循环结果的列表(存在results字段),我们可以通过过滤这个列表来提取符合条件的用户:

- name: Get all users in system
  shell: cat /etc/passwd | awk -F':' '{ print $1}'
  register: users

- set_fact:
    all_users: "{{ users.stdout_lines }}"

- name: Check if target file exists in user home
  file:
    path: "/home/{{ item }}/your-target-file"  # 替换为实际要检查的文件名
    state: file
  register: file_check_results
  loop: "{{ all_users }}"
  ignore_errors: true  # 避免文件不存在时任务直接失败

- name: Generate list of users with existing target file
  set_fact:
    new_user_list: >-
      {{
        file_check_results.results
        | selectattr('stat.exists', 'equalto', true)
        | map(attribute='item')
        | list
      }}

关键说明
  • file_check_results.results:存储了每个用户的文件检查结果,每个元素包含item(当前循环的用户名)和stat(文件状态详情)
  • selectattr('stat.exists', 'equalto', true):过滤出文件存在的结果项
  • map(attribute='item'):从过滤后的结果中提取对应的用户名
  • ignore_errors: true:必须添加,否则只要有一个用户的目标文件不存在,整个任务就会失败,无法完成后续的过滤操作

另外,推荐用Ansible内置的getent模块替代shell命令获取用户列表,更可靠且跨平台:

- name: Get all system users via getent
  getent:
    database: passwd
  register: passwd_entries

- set_fact:
    all_users: "{{ passwd_entries | json_query('values[*].0') }}"

内容的提问来源于stack exchange,提问作者Ima_Sys

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 07:26:06