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

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

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

目前我有:

  - name: Make a copy
    copy:
      src: original.cnf
      dest: copy.cnf
      force: no
  - name: Modify
    ini_file:
      path: copy.cnf
      section: ...
      option: ...
      value: ...

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

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

答案1

- block:
  name: These two are changed every time as modifications are not in original.cnf
  - name: Make a temporary copy
    copy:
      src: original.cnf
      dest: temp.cnf
      force: yes
  - name: Modify temporary copy
    ini_file:
      path: temp.cnf
      section: ...
      option: ...
      value: ...

- block:
  name: With same original.cnf and same modifications, the result will be already installed
  - name: Idempotent copy into place
    register: openssl_config_install
    copy:
      src: temp.cnf
      dest: copy.cnf
      force: yes


- assert:
    that:
      - openssl_config_install is not changed

答案2

根据 John 的回答,我最终得到了以下剧本片段。重要的部分是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

相关内容