Ansible 替换文本行:存在则替换,不存在则追加,文件不存在则创建
"""\n---\n- name: 替换或追加文本行\n hosts: localhost\n gather_facts: false\n\n tasks:\n - name: 检查文件是否存在\n stat:\n path: /path/to/file.txt\n register: file_stat\n\n - name: 创建文件\n file:\n path: /path/to/file.txt\n state: touch\n when: not file_stat.stat.exists\n\n - name: 替换或追加文本行\n lineinfile:\n path: /path/to/file.txt\n line: '要替换或追加的文本行'\n state: present\n when: file_stat.stat.exists\n"""\n将上述 Playbook 中的 /path/to/file.txt 替换为你要操作的文件的路径,将 要替换或追加的文本行 替换为你要替换或追加的文本内容。\n\n在运行该 Playbook 时,如果文件不存在,将会使用 file 模块创建文件,并使用 lineinfile 模块追加指定的文本行。如果文件已经存在,则会使用 lineinfile 模块替换匹配到的文本行。\n\n注意:为了示例简单,上述 Playbook 中的 hosts 参数设置为 localhost,你可以根据自己的需求修改该参数。
原文地址: https://www.cveoy.top/t/topic/pVP9 著作权归作者所有。请勿转载和采集!