使用ansible模板但rysnc来移动文件

Qui*_*Par 6 networking templates copy ansible

我有很多文件(Nginx配置)是模板的候选者,但我想使用rysnc/synchronize模块移动它们.

有没有办法实现这个目标?

现在我这样做

- name: Copy configuration 
  synchronize:
   src: "{{ nginx_path }}/"
   dest: /etc/nginx/
   rsync_path: "sudo rsync"
   rsync_opts:
    - "--no-motd"
    - "--exclude=.git"
    - "--exclude=modules"
    - "--delete"
  notify:
   - Reload Nginx
Run Code Online (Sandbox Code Playgroud)

模板引擎与移动/复制操作相结合,因此我无法使用它来应用模板并将其保存在源本身中,然后使用rsync移动它.

编辑:
改写这个的另一种方法是:

有没有办法应用模板,并将应用的输出保存在源机器本身?

Chr*_*ris 5

不是在单个任务中。但是,我相信以下剧本存根可以实现您的愿望:

---

- hosts: localhost
  gather_facts: no

  tasks:

  - name: "1. Create temporary directory"
    tempfile:
      state: directory
    register: temp_file_path

  - name: "2. Template source files to temp directory"
    template:
      src: "{{ item }}"
      dest: "{{ temp_file_path.path }}/{{ item | basename | regex_replace('.j2$', '') }}"
    loop: "{{ query('fileglob', 'source/*.j2') }}"
    delegate_to: localhost

  - name: "3. Sync these to the destination"
    synchronize:
      src: "{{ temp_file_path.path }}/"
      dest: "dest"
      delete: yes

  - name: "4. Delete the temporary directory (optional)"
    file:
      path: "{{ temp_file_path.path }}"
      state: absent
Run Code Online (Sandbox Code Playgroud)

解释:

为了测试,这个剧本被编写为目标本地主机并使用本地方法连接,我开发它来简单地查找 ./source/*.j2 中的所有 .j2 文件,并将创建的文件 rsync 到我工作站上的 ./dest/ 。我运行它使用ansible-playbook -i localhost, playbook_name.yml --connection=local

任务 1. 我们将首先将源文件模板化到本地主机(使用delegate_to: localhost模板任务上的选项)。您可以创建一个特定目录来执行此操作,也可以使用 Ansible 的 tempfile 模块在 /tmp 下的某处(通常)创建一个。

任务 2. 使用模板模块将在“./source/”中找到的 jinja 模板(具有以 .j2 结尾的任意文件名)转换为写入到上面任务 1 中创建的目录的输出文件。

任务 3. 使用同步模块将这些 rsync 同步到目标服务器(为了测试,我在同一台机器上使用了 ./dest)。

任务 4. 删除在上述任务 1 中创建的临时目录。