I'm using Ansible's blockinfile
module to add a block of lines between specific lines in a file. The block should be indented with 8 spaces. However, when I run the playbook, the lines are inserted at the beginning of the line (no indentation), ignoring the spaces I added in the block. Here's the playbook I'm using:
- name: Add lines between specific lines with 8 spaces of indentation
hosts: all
tasks:
- name: Add lines
ansible.builtin.blockinfile:
path: /path/to/my/file
marker: "# {mark} Do not edit manually"
insertbefore: '^\s*the line that exists'
block: |
# first line
second line
Expected behavior: The block should be inserted like this, with 8 spaces of indentation:
# BEGIN ANSIBLE MANAGED BLOCK
# first line
second line
# END ANSIBLE MANAGED BLOCK
Actual behavior: The block is inserted without indentation:
# BEGIN ANSIBLE MANAGED BLOCK
# first line
second line
# END ANSIBLE MANAGED BLOCK
I've tried adding spaces directly in the block, but they are being ignored. Is there a way to make blockinfile
respect the indentation for the inserted block?
This is YAML, add the indentation indicator/marker as all indents are the same.
Note the number two "2" after the pipe "|" in the first line of the following example:
block: |2
# first line
second line
third line with extra indent
Will tell the parser to only use the first two space characters for indentation and the other space characters to be part of the multiline string (scalar) mapped to the string "block" (scalar, in Ansible called parameter).
See 8.1.2. Literal Style (yaml.org) and 8.1.1.1. Block Indentation Indicator (yaml.org).
Compare How do I break a string in YAML over multiple lines? (Q&A).
Read about YAML Multiline strings in a more inclusive language on https://yaml-multiline.info/.