Ansible: Insert line if not exists

后端 未结 10 1300
庸人自扰
庸人自扰 2020-12-25 11:27

I\'m trying insert a line in a property file using ansible. I want to add some property if it does not exist, but not replace it if such property already exists in the file.

10条回答
  •  执笔经年
    2020-12-25 11:32

    Same idea as presented here : https://stackoverflow.com/a/40890850/7231194

    Steps are:

    • Try to replace the line.
    • If replace mod change it, restore
    • If replace mod doesn't change, add the line

    Example

    # Vars
    - name: Set parameters
      set_fact:
        ipAddress    : "127.0.0.1"
        lineSearched : "couchbase.host={{ ipAddress }}"
        lineModified : "couchbase.host={{ ipAddress }} hello"
    
    # Tasks
    - name: Try to replace the line
      replace:
        dest    : /dir/file
        replace : '{{ lineModified }} '
        regexp  : '{{ lineSearched }}$'
        backup  : yes
     register  : checkIfLineIsHere
    
    # If the line not is here, I add it
    - name: Add line
      lineinfile:
      state   : present
      dest    : /dir/file
      line    : '{{ lineSearched }}'
      regexp  : ''
      insertafter: EOF
    when: checkIfLineIsHere.changed == false
    
    # If the line is here, 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
    

提交回复
热议问题