如何在Ansible的blockinfile中的块开头添加空格?

Chr*_*s F 14 ansible ansible-2.x

我发现了这个blockinfile问题,用户建议在"|"之后添加一个数字 在"块:|" 行,但给出语法错误.基本上,我想使用blockinfile模块在文件中添加一个行块,但我希望块在文件中缩进6个空格.这是任务

- name: Added a block of lines in the file
  blockinfile:
  dest: /path/some_file.yml
  insertafter: 'authc:'
  block: |
    line0
      line1
      line2
      line3
        line4
Run Code Online (Sandbox Code Playgroud)

我预计

  authc:
    line0
      line1
      line2
      line3
        line4
Run Code Online (Sandbox Code Playgroud)

但得到

  authc:
line0
  line1
  line2
  line3
    line4
Run Code Online (Sandbox Code Playgroud)

在行的开头添加空格不会这样做.我怎么能做到这一点?

ant*_*tex 31

您可以使用名为"Block Indentation Indicator"的YAML功能:

- name: Added a block of lines in the file
  blockinfile:
  dest: /path/some_file.yml
  insertafter: 'authc:'
  block: |2
      line0
        line1
        line2
        line3
          line4
Run Code Online (Sandbox Code Playgroud)

这是关于|之后的2

参考文献:

  • 一些事情,首先这应该是正确的答案!其次,这是[**not broken**](https://github.com/ansible/ansible/issues/23777),而是块的解释从"Block Indentation Indicator"开始,正如答案正确演示的那样.请注意,答案代码中的第一行在`block:| 2`行下面有四个空格.这被解释为意味着在2个空格(每行)之后插入的下一个块开始,这将导致文件在插入第一行之前有2个空格. (6认同)
  • [**当前已损坏**](https://groups.google.com/forum/#!topic/ansible-project/mmXvhTh6Omo) 自 Ansible 版本 `2.1` 起,至少到 `2.3.1.0` (2认同)
  • 不,这不适用于当前版本的 ansible。似乎最多只能缩进 2 个空格。之后无论如何都只会做2个空格。 (2认同)

Nor*_*tol 10

后面的数字|描述了该块缩进了多少行。例如:

  block: |2
    insert some stuff
  ^^ 2 spaces here.

  block: |4
      insert some stuff
  ^^^^ 4 spaces here.
Run Code Online (Sandbox Code Playgroud)

如果您想在目标文件中缩进行,可以使用以下解决方法:

  block: |
    # this is a comment
      insert some stuff
Run Code Online (Sandbox Code Playgroud)

在此示例中,该行# this is a comment不会缩进,并且该行将insert some stuff有 2 个前导空格。


sta*_*tor 10

您可以使用 Jinja2缩进过滤器添加所需的缩进:

- name: Added a block of lines in the file
  blockinfile:
    dest: /path/some_file.yml
    insertafter: 'authc:'
    block: |
      {% filter indent(width=4, first=true) %}
      line0
        line1
        line2
        line3
          line4
      {% endfilter %}
Run Code Online (Sandbox Code Playgroud)

结果:

  authc:
    line0
      line1
      line2
      line3
        line4
Run Code Online (Sandbox Code Playgroud)