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

后端 未结 8 1996
粉色の甜心
粉色の甜心 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:19

    Another solution, also useful for other purposes is to loop over the contents of the file, line by line

    - name: get the file
      slurp:
        src: /etc/locale.gen
      register: slurped_file
    
    - name: initialize the matches list
      set_fact:
        MATCHES: []
    
    - name: collect matches in a list
      set_fact:
        MATCHES: "{{ MATCHES + [line2match] }}"
      loop: "{{ file_lines }}"
      loop_control:
        loop_var: line2match
      vars:
        - decode_content: "{{ slurped_file.content | b64decode }}"
        - file_lines: "{{ decode_content.split('\n') }}"
      when: '"BE" in line2match'
      
    - name: report matches if any
      debug:
        msg: "Found {{ MATCHES | length }} matches\n{{ MATCHES }}"
      when: 'listlen | int > 0'
      vars:
        listlen: "{{ MATCHES | length }}"
    

    This mechanism can be use to get a specific value from a matched line if you use it for example with the jinja regex_replace filter

    0 讨论(0)
  • 2020-12-01 03:21

    Use ansible lineinfile command, but this command will update the file with the line if it does not exists.

    - lineinfile: dest=/tmp/my.conf line='127.0.0.1' state=present
    
    0 讨论(0)
提交回复
热议问题