Ansible: Insert line if not exists

后端 未结 10 1216
庸人自扰
庸人自扰 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:47

    Looks like it does not work if you use backrefs.

    Following sample does not add a line

    - name: add hosts file entry
      lineinfile:
        path: "/etc/hosts"
        regexp: "foohost"
        line:  "10.10.10.10 foohost"
        state: present
        backrefs: yes
    

    After removing backrefs I got my line added to the file

    - name: add hosts file entry
      lineinfile:
        path: "/etc/hosts"
        regexp: "foohost"
        line:  "10.10.10.10 foohost"
        state: present
    
    0 讨论(0)
  • 2020-12-25 11:54

    By a long way of "Trials and errors" I come to this:

    - name: check existence of line in the target file
      command: grep -Fxq "ip addr add {{ item }}/32 dev lo label lo:{{ app | default('app') }}" /etc/rc.local
      changed_when: false
      failed_when: false
      register: ip_test
      with_items:
        - "{{ list_of_ips }}"
    
    - name: add autostart command
      lineinfile: dest=/etc/rc.local 
                  line="ip addr add {{ item.item }}/32 dev lo label lo:{{ app | default('app') }}"
                  insertbefore="exit 0"
                  state=present
      when: item.rc == 1
      with_items:
        - "{{ ip_test.results }}"
    
    0 讨论(0)
  • 2020-12-25 11:56

    We have tried the below and it worked well. our scenario need to entry "compress" in syslog file if it does not exist.

    - name: Checking compress entry present if not add entry   
      lineinfile:
        path: /etc/logrotate.d/syslog
        regexp: "    compress"
        state: present
        insertafter: "    missingok"
        line: "    compress"
    
    0 讨论(0)
  • 2020-12-25 11:57
    - name: add couchbase.host to properties, works like add or replace
      lineinfile: 
        state: present
        dest: /database.properties 
        regexp: '^couchbase.host'
        line: 'couchbase.host=127.0.0.1'
    
    0 讨论(0)
提交回复
热议问题