现在我在ansible中使用一个shell脚本,如果它在多行上会更加可读
- name: iterate user groups
shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} ....more stuff to do
with_items: "{{ users }}"
Run Code Online (Sandbox Code Playgroud)
只是不确定如何在Ansible shell模块中允许多行脚本
lar*_*sks 210
Ansible在其剧本中使用YAML语法.YAML有许多块运算符:
这>是一个折叠块操作符.也就是说,它通过空格将多条线连接在一起.以下语法:
key: >
This text
has multiple
lines
Run Code Online (Sandbox Code Playgroud)
将值赋值This text has multiple lines\n给key.
该|字符是文字块运算符.这可能是您想要的多行shell脚本.以下语法:
key: |
This text
has multiple
lines
Run Code Online (Sandbox Code Playgroud)
将值赋值This text\nhas multiple\nlines\n给key.
您可以将此用于多行shell脚本,如下所示:
- name: iterate user groups
shell: |
groupmod -o -g {{ item['guid'] }} {{ item['username'] }}
do_some_stuff_here
and_some_other_stuff
with_items: "{{ users }}"
Run Code Online (Sandbox Code Playgroud)
有一点需要注意:Ansible对shell命令的参数进行了一些简洁的操作,因此虽然上述内容通常会按预期工作,但以下情况不会:
- shell: |
cat <<EOF
This is a test.
EOF
Run Code Online (Sandbox Code Playgroud)
Ansible实际上会使用前导空格呈现该文本,这意味着shell永远不会EOF在行的开头找到该字符串.您可以通过使用如下cmd参数来避免Ansible无益的启发式:
- shell:
cmd: |
cat <<EOF
This is a test.
EOF
Run Code Online (Sandbox Code Playgroud)
Mar*_*ani 14
提到YAML延续线.
作为一个例子(尝试使用ansible 2.0.0.2):
---
- hosts: all
tasks:
- name: multiline shell command
shell: >
ls --color
/home
register: stdout
- name: debug output
debug: msg={{ stdout }}
Run Code Online (Sandbox Code Playgroud)
shell命令折叠为一行,如 ls --color /home
我更喜欢这种语法,因为它允许为 shell 设置配置参数:
---
- name: an example
shell:
cmd: |
docker build -t current_dir .
echo "Hello World"
date
chdir: /home/vagrant/
Run Code Online (Sandbox Code Playgroud)
小智 5
在 EOF 分隔符之前添加一个空格可以避免 cmd:
- shell: |
cat <<' EOF'
This is a test.
EOF
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79927 次 |
| 最近记录: |