Only check whether a line present in a file (ansible)

后端 未结 8 2080
粉色の甜心
粉色の甜心 2020-12-01 02:36

In ansible, I need to check whether a particular line present in a file or not. Basically, I need to convert the following command to an ansible task. My goal is to only che

8条回答
  •  不知归路
    2020-12-01 03:17

    Another way is to use the "replace module" then "lineinfile module".

    The algo is closed to the one used when you want to change the values of two variables.

    • First, use "replace module" to detect if the line you are looking for is here and change it with the something else. (Like same line + something at the end).
    • Then if "replace" is true, It means your line is here then replace the new line with a particularity, with the new line looking.
    • Else the line you are looking for is not here.

    Example:

    # Vars
    - name: Set parameters
      set_fact:
        newline      : "hello, i love ansible"
        lineSearched : "hello"
        lineModified : "hello you"
    
    # Tasks
    - name: Try to replace the line
      replace:
        dest    : /dir/file
        replace : '{{ lineModified }} '
        regexp  : '{{ lineSearched }}$'
        backup  : yes
      register  : checkIfLineIsHere
    
    - name: Line is here, change it
      lineinfile:
        state   : present
        dest    : /dir/file
        line    : '{{ newline }}'
        regexp  : '{{ lineModified }}$'
      when: checkIfLineIsHere.changed
    
    • If the file contains "hello", it will become "hello you" then "hello, i love ansible" at the end.
    • If the file content doesn't contain "hello", the file is not modified.

    With the same idea, you can do something if the lineSearched is here:

    # Vars
    - name: Set parameters
      set_fact:
        newline      : "hello, i love ansible"
        lineSearched : "hello"
        lineModified : "hello you"
    
    # Tasks
    - name: Try to replace the line
      replace:
        dest    : /dir/file
        replace : '{{ lineModified }} '
        regexp  : '{{ lineSearched }}$'
        backup  : yes
      register  : checkIfLineIsHere
    
    # If the line is here, I want to add something.
    - name: If line is here, do something
      lineinfile:
        state   : present
        dest    : /dir/file
        line    : '{{ newline }}'
        regexp  : ''
        insertafter: EOF
      when: checkIfLineIsHere.changed
    
    # But I still want this line in the file, Then restore it
    - name: Restore the searched line.
      lineinfile:
        state   : present
        dest    : /dir/file
        line    : '{{ lineSearched }}'
        regexp  : '{{ lineModified }}$'
      when: checkIfLineIsHere.changed
    
    • If the file contains "hello", the line will still contain "hello" and "hello, i love ansible" at the end.
    • If the file content doesn't contain "hello", the file is not modified.

提交回复
热议问题