使用可靠的部署模板文件的文件夹

有没有一种简单的方法来部署一个文件夹模板.j2文件夹到一个linux的盒子,使用相同的名称作为模板,但没有.j2扩展名,而不是使用每个文件的模板模块?

现在我有一个很长的名单:

- name: create x template template: src=files/x.conf.j2 dest=/tmp/x.conf owner=root group=root mode=0755 notify: - restart myService 

您可以使用with_fileglob从您的模板目录中获取文件列表,并使用filterwith_fileglob这样的j2扩展。

 - name: create x template template: src={{ item }} dest=/tmp/{{ item | basename | regex_replace('\.j2','') }} with_fileglob: - ../templates/*.j2 

Michael DeHaan(Ansible的创始人)在CoderWall上发表了一篇关于非常类似的问题的文章。 您可以根据需要调整和扩展它(如权限和所有权)。 相关部分的post在这里:


这可以通过使用“ with_items ”和单个notify语句来简化。 如果任何任务发生变化,服务将以与在剧本运行结束时需要重新启动的方式完全相同的方式通知。

  - name: template everything for fooserv template: src={{item.src}} dest={{item.dest}} with_items: - { src: 'templates/foo.j2', dest: '/etc/splat/foo.conf' } - { src: 'templates/bar.j2', dest: '/etc/splat/bar.conf' } notify: - restart fooserv 

请注意,由于我们的任务需要多个唯一的参数,因此我们不只是在“ template: ”行中说“ item ”,而是使用带有hash(dictionary)variables的with_items 。 如果你喜欢,你也可以使用列表来缩短它。 这是一个风格偏好:

  - name: template everything for fooserv template: src={{item.0}} dest={{item.1}} with_items: - [ 'templates/foo.j2', '/etc/splat/foo.conf' ] - [ 'templates/bar.j2', '/etc/splat/bar.conf' ] notify: - restart fooserv 

当然,我们也可以在另一个文件中定义列表,比如“ groupvars/webservers ”文件来定义webservers组所需的所有variables,或者从playbook中的“ varsfiles ”指令加载的YAML文件。 看看如果我们这样做可以清理。

 - name: template everything for fooserv template: src={{item.src}} dest={{item.dest}} with_items: {{fooserv_template_files}} notify: - restart fooserv 

罗素的答案确实有效,但需要改进

 - name: create x template - template: src={{ item }} dest=/tmp/{{ item | basename | regex_replace('.j2','') }} - with_fileglob: - files/*.j2 

所有$需要冷杉,因为它是错误的正则expression式regex_replace。 其次,所有的文件应该在文件目录而不是模板目录中

我写了一个文件树查找插件,可以帮助文件树的行动。

您可以在文件树中recursion文件,并根据文件属性执行操作(例如模板或复制)。 由于返回了相对path,因此您可以轻松地在目标系统上重新创build文件树。

 - name: Template complete tree template: src: '{{ item.src }}' dest: /web/{{ item.path }} force: yes with_filetree: some/path/ when: item.state == 'file' 

它使更多可读的剧本。

有可能从目录中自动获取实际文件的列表,并在之后进行迭代。

 - name: get the list of templates to transfer local_action: "shell ls templates/* | sed 's~.*/~~g'" register: template_files - name: iterate and send templates template: src=templates/{{ item }} dest=/mydestination/{{ item }} with_items: - "{{ template_files.stdout.splitlines() }}" 

下面的命令为我工作,对模板中的j2文件进行recursion查找并将其移动到目的地。 希望它可以帮助有人寻find目的地的模板的recursion副本。

  - name: Copying the templated jinja2 files template: src={{item}} dest={{RUN_TIME}}/{{ item | regex_replace(role_path+'/templates','') | regex_replace('\.j2', '') }} with_items: "{{ lookup('pipe','find {{role_path}}/templates -type f').split('\n') }}"