在 Ansible playbook 中使用 SED 时,可能会遇到以下两种常见问题:
问题一:出现错误消息“‘sed: -e expression #1, char xx: unterminated `s' command”。
问题二:无法找到文件或文件路径。
为解决这些问题,我们可以参考下面的代码示例进行操作。
示例一:
- name: Edit file using SED
become: true
become_method: sudo
lineinfile:
path: /etc/hosts
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
with_items:
- { regexp: '^127.0.0.1', line: '127.0.0.1 localhost' }
- { regexp: '^::1', line: '::1 localhost ip6-localhost ip6-loopback' }
这个示例使用 Ansible 中的 lineinfile 模块来替换文件中的行。使用这个模块,我们可以避免 SED 带来的终止错误消息。
示例二:
- name: Edit file using SED
become: true
become_method: sudo
shell: "sed -i 's#^{{ search_for }}={{ current_value }}#{{ search_for }}={{ new_value }}#g' {{ file_path }}"
vars:
search_for: "FOO"
current_value: "bar"
new_value: "baz"
file_path: "/etc/sysconfig/network"
这个示例使用 SED 来替换文件中的一个特定字符串。请注意,这个示例在 file_path 变量中指定了文件路径。使用变量来设置文件路径可以避免找不到文件或文件路径的问题。
总之,在 Ansible playbook 中使用 SED 需要小心,应避免出现不必要的错误。我们可以使用 Ansible 中的其他模块和工具来避免这些错误。