首页 > 解决方案 > 如果文件有模式,如何在 Ansible 中跳过模板副本?

问题描述

如果目标文件中没有字符串,则尝试仅复制 Nginx 配置文件。

我认为这会起作用:

- name: Copy nginx config file
  template:
    src: templates/nginx.conf
    dest: /etc/nginx/sites-enabled/default
    validate: grep -l 'managed by Certbot' %s

但是,如果文件中没有“由 Certbot 管理”并停止 playbook 运行,则此任务将失败。

如果目标文件已经具有该模式,我该如何跳过模板副本?也许有更好的方法来获得相同的结果?

标签: ansible

解决方案


灵感来自另一个答案

您可以使用检查模式下的lineinfile模块检查文件中是否存在内容。然后,您可以将结果用作模板任务的条件。in条件是为了default应对文件不存在且found属性不在注册结果中的情况。

---
- name: Check for presence of "managed by Certbot" in file
  lineinfile:
    path: /etc/nginx/sites-enabled/default
    regexp: ".*# managed by Certbot.*"
    state: absent
  check_mode: yes
  changed_when: false
  register: certbot_managed

- name: Copy nginx config file when not certbot managed
  template:
    src: templates/nginx.conf
    dest: /etc/nginx/sites-enabled/default
  when: certbot_managed.found | default(0) == 0

推荐阅读