Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add spaces at beginning of block in Ansible's blockinfile?

Tags:

I found this blockinfile issue, where a user suggested adding a number after the "|" in the "block: |" line, but gives a syntax error. Basically, I want to use blockinfile module to add a block of lines in a file, but I want the block to be indented 6 spaces in the file. Here's the task

- name: Added a block of lines in the file   blockinfile:   dest: /path/some_file.yml   insertafter: 'authc:'   block: |     line0       line1       line2       line3         line4 

I expect

  authc:     line0       line1       line2       line3         line4 

but get

  authc: line0   line1   line2   line3     line4 

Adding spaces in the beginning of the lines does not do it. How can I accomplish this?

like image 666
Chris F Avatar asked Sep 27 '16 18:09

Chris F


People also ask

How do you add spaces in Ansible?

You basically need to put as many spaces as necessary before elements. And use \n for newlines.

What is marker in Ansible?

Ansible blockinfile module is used to insert/update/remove a block of lines. The block will be surrounded by a marker, like begin and end, to make the task idempotent. If you want to modify/ insert only a line, use lineinfile module.

Which module will insert update remove multi line text in a file?

blockinfile module – Insert/update/remove a text block surrounded by marker lines.


2 Answers

You can use a YAML feature called "Block Indentation Indicator":

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

It's all about the 2 after the |

References:

  • https://groups.google.com/forum/#!topic/ansible-project/mmXvhTh6Omo
  • In YAML, how do I break a string over multiple lines?
  • http://www.yaml.org/spec/1.2/spec.html#id2793979
like image 153
antex Avatar answered Oct 01 '22 04:10

antex


The number after the | describes how many lines the block is indented. For example:

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

If you like to indent your line in the destination file you can use this workaround:

  block: |     # this is a comment       insert some stuff 

In this example, the line # this is a comment will not be indented and the line insert some stuff will have 2 leading spaces.

like image 30
Nortol Avatar answered Oct 01 '22 03:10

Nortol