我有很多文件(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

模板引擎与移动/复制操作结合在一起,因此,我无法使用它来应用模板并将其保留在源代码本身中,然后使用rsync对其进行移动。

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

有没有办法应用模板,并将应用的输出保留在源计算机本身中?

最佳答案

不在一个任务中。但是,下面的剧本 stub 实现了您所希望的:

---

- 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

解释:

为了进行测试,将这本剧本写到目标localhost并使用本地方法进行连接,我将其开发为仅在./source/*.j2中查找所有.j2文件,然后将创建的文件重新同步到我的工作站上的./dest/。我使用ansible-playbook -i localhost, playbook_name.yml --connection=local运行了它

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

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

任务3.使用syncize模块将这些rsync同步到目标服务器(为进行测试,我在同一框中使用./dest)。

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

关于templates - 使用ansible模板,但使用rysnc移动文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51486767/

10-11 22:43
查看更多