尝试列出主机上的所有用户时出错

Getting error when try to list all users on the hosts

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

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

请注意,默认情况下,Ansible 使用 /bin/sh,如命令的 synopsis 所示。

It is almost exactly like the ansible.builtin.command module but runs the command through a shell (/bin/sh) on the remote node.

来源: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. 指定要通过 bash 执行的 shell 任务:
    - shell: getent passwd {1000..6000} | cut -d":" -f1
      register: getent
      args:
        executable: /bin/bash