linux - Ansible:如何使用 shell 处理引号和空格

标签 linux ansible redhat quotes

我正在创建一个 playbook 以在 ansible 2.8.2 上使用以下 playbook 列出“/home”目录中的用户:

---
- name: Check users in /home directory
  hosts: REDHAT
  tasks:
  - name: List users
      shell: cat /etc/passwd | grep "/home" |cut -d ":" -f1| tr '\n' ' '
      register: output
      ignore_errors: yes

我遇到的问题是在带有引号和空格的命令末尾:'\n' ' '

我已经尝试使用双引号 ", {} 和 [] 但我仍然有语法错误

当我使用---syntax-check时的结果:

> The offending line appears to be:

  - name: List users
      shell: cat /etc/passwd | grep "/home" |cut -d ":" -f1| tr "'\n' ' '"
           ^ here
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes. If starting a value with a quote, make sure the
line ends with the same set of quotes. For instance this arbitrary
example:

    foo: "bad" "wolf"

Could be written as:

    foo: '"bad" "wolf"'

在这种情况下我什么时候必须使用引号

最佳答案

花 Y 分钟阅读 Learn yaml in Y minute您将在其中了解到:

[Yaml is] a strict superset of JSON, with the addition of syntactically significant newlines and indentation, like Python. Unlike Python, however, YAML doesn’t allow literal tab characters for indentation.

您的问题根本不在于引号,而在于您的 shell 任务中代码的缩进:

---
- name: Check users in /home directory
  hosts: REDHAT
  tasks:
    - name: List users
      shell: cat /etc/passwd | grep "/home" |cut -d ":" -f1| tr '\n' ' '
      register: output
      ignore_errors: yes

请注意,使用 yamllint在你上面的文件中给出了一个稍微更精确的错误:

$ yamllint playbook_test.yml 
playbook_test.yml
  6:12      error    syntax error: mapping values are not allowed here

关于linux - Ansible:如何使用 shell 处理引号和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58239428/

相关文章:

jenkins - Ansible 是否可以替代 Hudson/Jenkins 等 CI 工具?

linux - yum 给出 multilib 版本错误

linux - 链接到 TLS libpthread-2.3.4.so 库而不是系统 libpthread 库

c - 使用 popen(3) 与系统交互的 C 程序与 bash shell 相比如何?

Ansible 用户定义的库存变量调用

c++ - 如何编译我的 C++ 项目?

shell - 如果存在则从 ansible playbook 中删除

Eclipse 中 Scientific Linux 上的 C++14

linux - "sed"命令的奇怪问题

linux - 是否可以在Linux命令行中使用 "py"代替 "python"?