我试图模板yum .repo文件 . 我们有多个内部和外部yum回购,我们管理的各种主机可能会或可能不会使用 .
我希望能够指定任意数量的repos以及它们将被模板化的.repo文件 . 将这些repos组合在同一个.repo文件中是有意义的,它们具有共同的目的(例如所有centos repos)
我无法确定如何结合ansible,yaml和j2来实现这一目标 . 我尝试过使用ansible'with_items','with_subelements'和'with_dict'失败 .
YAML data
yum_repo_files:
- centos:
- name: base
baseurl: http://mirror/base
- name: updates
baseurl: http://mirror/updates
- epel:
- name: epel
baseurl: http://mirror/epel
Ansible task
- name: create .repo files
template: src=yumrepos.j2 dest="/etc/yum.repos.d/{{ item }}.repo"
with_items: yum_repo_files
j2 template
{% for repofile in yum_repo_files.X %} {# X being the relative index for the current repofile, e.g. centos = 0 and epel = 1 #}
{% for repo in repofile %}
name={{ repo.name }}
baseurl={{ repo.baseurl }}
{% endfor %}
{% endfor %}
3 回答
当您将
with_items
与模板模块一起使用时,特殊变量_2659850将被传递到您的jinja模板中 .试试这个:
user24364的答案帮助解决了一半的问题,然后我使用了一些python方法从列表和dicts中获取正确的数据 .
提供完整的文件名'centos.repo'而不是'centos'简化了逻辑(并且与其他任务的逻辑更好地对齐):
. itemskeys()和.next()方法用于项目,以获取dicts列表中的repo文件名:
.itervalues()方法用于获取包含每个给定repo的所有键/值的dicts列表:
我还添加了一些其他任务来清理非托管文件等 . 一旦我清理了代码,我就会把它发布到ansible galaxy,因为似乎没有其他人共享这样的角色 .
您的文件将命名为:* .repo.j2;那么,你可以使用fileglob:
参考:
https://serverfault.com/questions/578544/deploying-a-folder-of-template-files-using-ansible