首页 > 解决方案 > 尝试列出主机上的所有用户时出错

问题描述

我正在尝试获取我在主机上创建的所有用户。当我在终端上运行以下命令时,我得到了机器上的所有用户。

sudo getent passwd {1000..6000} | cut -d":" -f1

但是,当我尝试使用 ansible 运行它时,出现错误。我试过用双引号括起来,转义括号,将输出管道传输到 cat 等,但没有任何效果。

---
- name: "run commands"
  become: true
  gather_facts: no
  hosts: all
  tasks:
    - name: list all users
      shell: getent passwd {1000..6000} | cut -d":" -f1
      register: getent

    - debug: var=getent.stdout_lines

标签: bashautomationansible

解决方案


请注意,默认情况下,Ansible 使用,正如命令概要/bin/sh中所指出的那样。

它几乎与ansible.builtin.command/bin/sh模块完全相同,但通过远程节点上的shell ( ) 运行命令。

来源:https ://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html#synopsis

sh不会解释像{0..10}.

有两种方法可以克服这个问题:

  1. seq而是 使用:
    - shell: getent passwd $(seq 1000 6000) | cut -d":" -f1
      register: getent
    
  2. 通过以下方式指定shell您希望它执行的任务bash
    - shell: getent passwd {1000..6000} | cut -d":" -f1
      register: getent
      args:
        executable: /bin/bash
    

推荐阅读