首页 > 解决方案 > 根据内容链接任务

问题描述

我有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

我遇到的问题是当行正确时正确的任务正在运行..所以我需要使用其他类型的标准来防止它在文件中的行正确时运行...如果文件中的行是错了它起作用了,因为它取代了它。

标签: regexansible

解决方案


这是 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 %}

推荐阅读