How to add multiple lines in Ansible

11,179

After playing a bit more on this I've discovered that I can do this:

 - name: Line test2
   blockinfile:
     path: /home/vagrant/abcd
     marker: "------"
     insertafter: '### AFTER THIS LINE PART 2'
     state: present
     block: |
       # This is line 1
       # This is line 2
       # This is line 3

Which produces this:

 ### AFTER THIS LINE PART 2
 ------
 # This is line 1
 # This is line 2
 # This is line 3
 ------

Which I think is acceptable for our requirements.

Thanks.

Share:
11,179

Related videos on Youtube

solaris
Author by

solaris

Interests include: OS: Red Hat, CentOS, Rocky Linux, Debian, Ubuntu, Tech: Ansible, Python, AWS, Terraform, Packer, Vagrant, Bash, AWK, SED, Regex, KVM, git, Docker, k8s, vim, tmux, conda, jupyter, pycharm HW: Raspberry Pi, HPE, Dell, VSphere Misc: Security, Mathematics

Updated on June 04, 2022

Comments

  • solaris
    solaris almost 2 years

    I am trying to add multiple lines to a config file after a match and using the lineinfile but I am finding that the resulting lines are reversed. Here is my playbook:

      - name: Line test
        lineinfile:
          path: /home/vagrant/abcd
          insertafter: '### AFTER THIS LINE'
          line: "{{ item }}"
          state: present
        with_items:
          - '# This is line 1'
          - '# This is line 2'
          - '# This is line 3' 
    

    and here is the result:

    ### AFTER THIS LINE
    # This is line 3
    # This is line 2
    # This is line 1
    

    My desired result should be:

    ### AFTER THIS LINE
    # This is line 1
    # This is line 2
    # This is line 3
    

    I understand that the reversal is due to the loop but how can one overcome this without reversing the order of the input? I know there is the blockinfile which puts the block of text as-is but that adds the "ANSIBLE MANAGED BLOCK" markers which I don't want.

    Thanks.

    • techraf
      techraf over 6 years
      Don't do it, you don't need to (everyone at some point thought they needed).
  • user2700022
    user2700022 about 4 years
    Anyone knows how to achieve this for a Windows host?