Ansible lineinfile模块:文件无指定行时在指定位置添加该行
Got it, let's solve this problem. You want to add a line to a file only if it doesn't exist anywhere in the file, and if it's missing, insert it right after a specific anchor line. Here's a clean, reusable Ansible playbook that does exactly what you need:
Ansible Playbook: Add Line Only If Not Present Anywhere
The core logic here is simple: first verify if the target line exists anywhere in the file. If it does, we do nothing. If it doesn't, we insert it immediately after your specified anchor line.
Playbook Code
--- - name: Ensure line is added only if missing entirely hosts: all vars: # Customize these variables to match your use case target_file: "/path/to/your/target/file" anchor_line: "foo" # Line to insert after line_to_add: "bar" # Line to add (if missing) tasks: - name: Check if target line exists in the file ansible.builtin.command: grep -q "{{ line_to_add }}" "{{ target_file }}" register: line_exists ignore_errors: true changed_when: false # This task doesn't modify anything, so mark as unchanged - name: Insert line after anchor if it's missing ansible.builtin.lineinfile: path: "{{ target_file }}" insertafter: "{{ anchor_line }}" line: "{{ line_to_add }}" state: present when: line_exists.rc != 0 # Only run if grep didn't find the line (rc=1)
How It Works
Let's break down the tasks with your example scenarios:
- Check for existing line: The first task uses
grep -qto silently check if"bar"is present in the file.- For
file1andfile3(which already contain "bar"),grepreturns exit code 0 → the second task is skipped. - For
file2(no "bar"),grepreturns exit code 1 → the second task runs.
- For
- Insert line if missing: The
lineinfilemodule adds"bar"right after the last occurrence of"foo". If"foo"doesn't exist in the file at all, this task won't add anything (since there's no anchor to insert after).
Optional Adjustments
- Insert after first anchor occurrence: If you want to add the line after the first instance of
"foo"instead of the last, addfirstmatch: yesto thelineinfiletask. - Handle non-existent files: If the target file might not exist, add a pre-task to create it (with the anchor line if needed) using the
copyorfilemodule.
内容的提问来源于stack exchange,提问作者ewok
相关产品推荐
相关产品推荐

