如何管理文件的修改副本?

Pet*_*etr 5 files copy ansible ansible-playbook

按照这个答案,我想复制 OpenSSL 的配置,并进行一组特定的更改。原始文件不受我的控制,因此我无法将其设为模板。

目前我有:

  - name: Make a copy
    copy:
      src: original.cnf
      dest: copy.cnf
      force: no
  - name: Modify
    ini_file:
      path: copy.cnf
      section: ...
      option: ...
      value: ...
Run Code Online (Sandbox Code Playgroud)

此更改序列是幂等的,但如果原始文件发生更改,则更改不会传播到副本。如果我将其更改为force: yes,则原始更改将被传播,但每次运行剧本时都会执行更改。这是有问题的,因为我需要在发生更改时重新启动依赖的服务,但显然这不能每次都发生。

有没有一种方法可以维护副本,以便当且仅当需要时才修改目标文件?

Pet*_*etr 2

根据约翰的回答,我最终得到了以下剧本片段。重要的部分是changed_when: False,它确保只有修改目标配置文件副本的步骤才算作更改。

- name: Create OpenSSL config copy
  block:
  - name: Create temporary file for the config's copy
    tempfile:
    register: tempfile
    changed_when: False
  - name: Copy openssl.cnf to the temporary file
    copy:
      src: "{{ openssl_cnf_source }}"
      dest: "{{ tempfile.path }}"
      mode: 0644  # Without this the next `copy` task can have issues reading the file.
    changed_when: False
  - name: Modify openssl.cnf in the temporary file
    ini_file:
      path: "{{ tempfile.path }}"
      section: ...
      option: ...
      value: ...
    changed_when: False
  - name: Copy the temporary file to the target OpenSSL config
    copy:
      src: "{{ tempfile.path }}"
      dest: "{{ openssl_cnf_copy }}"
      mode: 0644
      owner: ...
    notify:
      - ...
  - name: Delete the temporary file
    file:
      path: "{{ tempfile.path }}"
      state: absent
    changed_when: False
Run Code Online (Sandbox Code Playgroud)