regex - 根据内容链接任务
问题描述
我有3个任务..
第一个任务检查文件是否包含<ip> <hostname>
模式
如果不存在寻求的字符串,第二个任务会添加一行。
如果线路不好,第三个任务会纠正线路。
这 3 个任务独立运行良好,但我想以某种方式将它们连接在一起。
我有以下使用模型 /etc/hosts 的剧本。
---
- name: check hosts playbook
hosts: centos
tasks:
- name: check whether a line in the form of '<ip> <hostname>' exists
lineinfile:
path: /var/tmp/hosts
regexp: '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s\w+'
state: absent
check_mode: true
register: line_exists
- name: append_host_file
lineinfile:
path: /var/tmp/hosts
insertafter: '^(127\.0\.0\.1|)(?:\d{1,3}\.){3}\d{1,3}'
line: '{{ ansible_default_ipv4.address }} {{ansible_hostname }}'
backup: yes
when: not line_exists.changed
- name: correct_hosts_file
lineinfile:
path: /var/tmp/hosts
regexp: '^(?!{{ ansible_default_ipv4.address }}\s{{ ansible_hostname }})(?:\d{1,3}\.){3}\d{1,3}\s\w+'
line: '{{ ansible_default_ipv4.address }} {{ansible_hostname }}'
when: line_exists.changed
我遇到的问题是当行正确时正确的任务正在运行..所以我需要使用其他类型的标准来防止它在文件中的行正确时运行...如果文件中的行是错了它起作用了,因为它取代了它。
解决方案
这是 lineinfile 的一个常见问题,它并没有看起来那么有用。
我的建议:将文件内容加载到变量(- command: cat /etc/hosts
)中,注册它(register: old_hosts
)而不是在模板中迭代该变量的每一行。
- name: get hosts
command: cat /etc/hosts
register: old_hosts
- name: write hosts
template:
src: hosts.j2
dest: /etc/hosts
主机.j2:
{% for line in old_hosts.stdout_lines %}
{% if line (....) %}
...
{% endif %}
{% endfor %}
推荐阅读
- behat - 如何修复 Behat 3 / Mink 中的浏览器窗口大小?
- angular - 如何在 ckeditor4-angular 中添加 MathType 插件以使用数学公式
- azure - 如何在 azure 上获取我的应用服务的 url
- javascript - 检查(验证)使用 ajax 发送表单数据
- node.js - 错误:数据和哈希必须是登录中的字符串
- flutter - 在颤动中将一个数字四舍五入到最接近的 100
- elasticsearch - 在 kibana 7.8.1 中将图形数据导出为 csv
- elasticsearch - 如何在 Grafana 中查找内存使用差异
- java - 得到一个 NullPointerException 并且不知道为什么
- javascript - 如何在 SFTP 服务器中获取文件的绝对路径