Search code examples
ansiblejinja2

How to append string to the end of a line in file on its first occurrence


Having below file content

Label abc
First line
Second line
Append line at the end of this line
Append line at the end of this line
Append line at the end of this line
Last line

How to append a string added string to the first occurrence of Append line at the end of this line using Ansible playbook

Label abc
First line
Second line
Append line at the end of this line added string 
Append line at the end of this line
Append line at the end of this line
Last line

I tried the below but the entire file content was modified

    - name: Replace only the first occurrence of a line in a file and append values
      hosts: localhost
      tasks:
        - name: Read the file content
          slurp:
            path: /path/to/your/file
          register: file_content
    
        - name: Modify only the first occurrence of the line and append values
          set_fact:
            updated_lines: >-
              {%- set found = False -%}
              {%- for line in (file_content.content | b64decode).split('\n') -%}
                {%- if not found and line.startswith('label Linux') -%}
                  {%- set found = True -%}
                  {{ line + ' your_append_text' }}
                {%- else -%}
                  {{ line }}
                {%- endif -%}
              {%- endfor -%}
    
        - name: Write the modified content back to the file
          copy:
            content: "{{ updated_lines | join('\n') }}"
            dest: /path/to/your/file
            backup: yes

Solution

  • Given the file

    shell> cat /tmp/ansible/file 
    Label abc
    First line
    Second line
    Append line at the end of this line
    Append line at the end of this line
    Append line at the end of this line
    Last line
    

    The below task does what you want

        - lineinfile:
            path: /tmp/ansible/file
            regexp: '^Append line at the end of this line.*$'
            line: 'Append line at the end of this line added string'
            firstmatch: true
    

    gives

    shell> cat /tmp/ansible/file 
    Label abc
    First line
    Second line
    Append line at the end of this line added string
    Append line at the end of this line
    Append line at the end of this line
    Last line
    

    The task is idempotent.


    Q: "Match the line dynamically."

    A: Substitute the variables. For example, the below task gives the same result

        - lineinfile:
            path: /tmp/ansible/file
            regexp: '^{{ target }}.*$'
            line: '{{ target }} {{ append }}'
            firstmatch: true
          vars:
            target: Append line at the end of this line
            append: added string