且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Ansible 中执行多行 shell 脚本

更新时间:2023-12-05 14:56:52

Ansible 在其剧本中使用 YAML 语法.YAML 有许多块操作符:

Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:

  • > 是一个折叠块操作符.也就是说,它通过空格将多行连接在一起.以下语法:

  • The > is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:

key: >
  This text
  has multiple
  lines

将值 This text has multiple lines\n 分配给 key.

| 字符是文字​​块运算符.这可能是您想要的多行 shell 脚本.以下语法:

The | character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:

key: |
  This text
  has multiple
  lines

将值 This text\nhas multiple\nlines\n 分配给 key.

您可以将其用于多行 shell 脚本,如下所示:

You can use this for multiline shell scripts like this:

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

有一个警告:Ansible 对 shell 命令的参数进行了一些笨拙的操作,因此虽然上述通常会按预期工作,但以下不会:

There is one caveat: Ansible does some janky manipulation of arguments to the shell command, so while the above will generally work as expected, the following won't:

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansible 实际上会渲染带有前导空格的文本,这意味着 shell 永远不会在一行的开头找到字符串 EOF.您可以像这样使用 cmd 参数来避免 Ansible 无用的启发式方法:

Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd parameter like this:

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF