参考yaml官网

yaml 文件中多行字符串可以使用 | 保留换行符,使用 > 将换行符替换为空格

多行字符串可以使用引号括起来:" " 会进行特殊字符转义,' ' 保留原始字符串。

| 示例

# vim test.yml
---
- name: test
  hosts: 127.0.0.1
  gather_facts: no
  tasks:
    - name: echo test
    # 换行符保留,输出三个 Line
      shell: |
        echo Line 1
        echo Line 2
        echo Line 3
      register: result
    - debug:
        msg: "{{ result.stdout_lines }}"

执行结果:

TASK [debug] *****************************************
ok: [127.0.0.1] => {
    # 可以看到三行输出
    "msg": [
        "Line 1", 
        "Line 2", 
        "Line 3"
    ]
}

> 示例

# vim test.yml
---
- name: test
  hosts: 127.0.0.1
  gather_facts: no
  tasks:
    - name: echo test
    # 换行符删除,输出一行
      shell: >
        echo Line 1
        echo Line 2
        echo Line 3
      register: result
    - debug:
        msg: "{{ result.stdout_lines }}"

执行结果:

TASK [debug] ********************************************
ok: [127.0.0.1] => {
    "msg": [
    # 只有一行输出,后面两行作为了 echo 的参数来执行,直接输出为原始字符串
        "Line 1 echo Line 2 echo Line 3"
    ]
}
> 模式下,空行和缩进表示保留换行

例如,调整上述 task 中的缩进,即可输出 | 相同内容

使用缩进
# vim test.yml
---
- name: test
  hosts: 127.0.0.1
  gather_facts: no
  tasks:
    - name: echo test
    # 缩进表示保留换行,结果为输出三行
      shell: >
        echo Line 1
          echo Line 2
        echo Line 3
      register: result
    - debug:
        msg: "{{ result.stdout_lines }}"

输出为:

TASK [debug] *******************************
ok: [127.0.0.1] => {
    "msg": [
        "Line 1", 
        "Line 2", 
        "Line 3"
    ]
}

需要注意,只能是以第一行为基准添加缩进来表示换行,如果减少缩进,则为语法错误。
错误示例:

      shell: >
          echo Line 1
        echo Line 2
        echo Line 3
使用空行
# vim test.yml
---
- name: test
  hosts: 127.0.0.1
  gather_facts: no
  tasks:
    - name: echo test
      # 输出为两行,后面两行作为一行输出
      shell: >
        echo Line 1
        
        echo Line 2
        echo Line 3
      register: result
    - debug:
        msg: "{{ result.stdout_lines }}"

结果:

TASK [debug] *******************************
ok: [127.0.0.1] => {
    "msg": [
        "Line 1", 
        "Line 2 echo Line 3"
    ]
}
+-

+ 表示保留文字块末尾的换行,- 表示删除字符串末尾的换行。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐