【问题标题】:Getting error when try to list all users on the hosts尝试列出主机上的所有用户时出错
【发布时间】:2021-06-02 10:54:57
【问题描述】:

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

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

【问题讨论】:

  • 错误信息是什么?

标签: bash automation ansible


【解决方案1】:

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

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

来源: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
    

【讨论】:

  • 谢谢,工作就像一个魅力,选择了第二个 :) 但也很高兴知道第一个选项。
猜你喜欢
  • 1970-01-01
  • 2021-04-13
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 2017-10-03
  • 2019-03-14
  • 1970-01-01
相关资源
最近更新 更多