如何在Ansible中执行多行Shell脚本 [英] How to do multiline shell script in Ansible

查看:4366
本文介绍了如何在Ansible中执行多行Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用ansible的shell脚本,如果该脚本位于多行上,则可读性会更高

right now I am using a shell script in ansible that would be much more readable if it was on multiple lines

- name: iterate user groups
  shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} ....more stuff to do
  with_items: "{{ users }}"

只是不确定如何在Ansible shell模块中允许多行脚本

Just not sure how to allow multiline script in Ansible shell module

推荐答案

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实际上将使用前导空格来呈现该文本,这意味着外壳程序将永远不会在行首找到字符串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

这篇关于如何在Ansible中执行多行Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆