有没有一种简单的方法可以将一个充满模板 .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
Run Code Online (Sandbox Code Playgroud)
小智 85
您可以使用with_fileglob
从模板目录中获取文件列表,并使用过滤器去除 j2 扩展名,如下所示:
- name: create x template
template:
src: "{{ item }}"
dest: /tmp/{{ item | basename | regex_replace('\.j2$', '') }}
with_fileglob:
- ../templates/*.j2
Run Code Online (Sandbox Code Playgroud)
Mxx*_*Mxx 21
Michael DeHaan(Ansible 的创建者)在CoderWall上发表了一篇文章,讨论了非常相似的问题。您可以根据自己的需要(如权限和所有权)对其进行调整和扩展。帖子的相关部分在这里:
这可以通过使用“ 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
Run Code Online (Sandbox Code Playgroud)
请注意,由于我们有采用多个唯一参数的任务,因此我们不只是item
在 ' template:
' 行中说“ ” ,而是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
Run Code Online (Sandbox Code Playgroud)
当然,我们也可以在另一个文件中定义您正在浏览的列表,例如“ groupvars/webservers
”文件来定义webservers
组所需的所有变量,或者从varsfiles
剧本中的“ ”指令加载的 YAML 文件。如果我们这样做,看看这会如何清理。
- name: template everything for fooserv
template: src={{item.src}} dest={{item.dest}}
with_items: {{fooserv_template_files}}
notify:
- restart fooserv
Run Code Online (Sandbox Code Playgroud)
Dag*_*ers 12
我写了一个文件树查找插件,可以帮助处理文件树的操作。
您可以递归文件树中的文件并根据文件属性执行操作(例如模板或复制)。由于返回了相对路径,您可以轻松地在目标系统上重新创建文件树。
- name: Template complete tree
template:
src: '{{ item.src }}'
dest: /web/{{ item.path }}
force: yes
with_filetree: some/path/
when: item.state == 'file'
Run Code Online (Sandbox Code Playgroud)
它使剧本更具可读性。
小智 9
罗素的答案确实有效,但需要改进
- name: create x template
- template: src={{ item }} dest=/tmp/{{ item | basename | regex_replace('.j2','') }}
- with_fileglob:
- files/*.j2
Run Code Online (Sandbox Code Playgroud)
所有 $ 的第一个都需要去,因为它是 regex_replace 中的错误正则表达式。其次所有文件都应该在文件目录而不是模板目录中
归档时间: |
|
查看次数: |
78753 次 |
最近记录: |