如何让 Ansible 的“调试”模块打印包含许多 ' 的字符串 ' 作为多行字符串?

问题描述 投票:0回答:2

我的 Ansible 变量之一定义为

- name: prepare the multiline message
  set_fact: 
    report_string: |
      THIS IS A TEST

      state of the machines
      ---------------------

      state of machines of level1: {{ machineslv1_state }}

      state of machines of level2: {{ machineslv2_state }}

      ...


      connection errors
      ---------------------

      connection errors of machines of level1: {{ machineslv1_errconn }}

      connection errors of machines of level2: {{ machineslv2_errconn }}

      ...
      ...
      ...

      END OF THE MESSAGE

我想在剧本执行期间打印这个变量的值,所以我做了这个任务

- name: show the report_string
  debug:
    msg: |
     "{{ report_string }}"

但是,Ansible 将其打印为单行字符串,其中行由 ' 连接 '.

是否可以将其打印为多行字符串?

string ansible multiline ansible-facts
2个回答
2
投票

请记住,

debug
模块只是......一个用于打印信息以帮助您调试事物的模块。它并不意味着产生格式良好的输出(如果需要,可以使用
template
模块将数据写入文件)。

也就是说,如果您通过拆分\n上的数据来打印

行列表
,您可能会得到更接近您想要的结果:

- hosts: localhost
  gather_facts: false
  tasks:
  - name: prepare the multiline message
    set_fact:
      report_string: |
        THIS IS A TEST

        state of the machines
        ---------------------

        state of machines of level1: ...
        state of machines of level2: ...

        END OF THE MESSAGE

  - debug:
      msg: "{{ report_string.splitlines() }}"

这会产生:

TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "msg": [
        "THIS IS A TEST",
        "",
        "state of the machines",
        "---------------------",
        "",
        "state of machines of level1: ...",
        "state of machines of level2: ...",
        "",
        "END OF THE MESSAGE"
    ]
}

0
投票

最后我发现依赖python更方便

- name: print the report_string using python
    command: /usr/bin/python
    args:
      stdin: |
        print(" ")
        print("""{{ report_string }}""")
        print(" ")
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.