sto*_*000 5 python jinja2 ansible
我有问题通过Jinja2和Ansible排序IP.这是我的变量和ansible模板的jinja2代码.
角色/ DNS /瓦尔/ main.yml:
---
DC1:
srv1:
ip: 10.2.110.3
srv2:
ip: 10.2.110.11
srv3:
ip: 10.2.110.19
srv4:
ip: 10.2.110.24
DC2:
srv5:
ip: 172.26.158.3
srv6:
ip: 172.26.158.11
srv7:
ip: 172.26.158.19
srv8:
ip: 172.26.158.24
Run Code Online (Sandbox Code Playgroud)
角色/ DNS /模板/ db.example.com.j2:
$TTL 86400
@ IN SOA example.com. root.example.com. (
2014051001 ; serial
3600 ; refresh
1800 ; retry
604800 ; expire
86400 ; minimum
)
; Name server
IN NS dns01.example.com.
; Name server A record
dns01.example.com. IN A 10.2.110.92
; 10.2.110.0/24 A records in this Domain
{% for hostname, dnsattr in DC1.iteritems() %}
{{hostname}}.example.com. IN A {{dnsattr.ip}}
; 172.26.158.0/24 A records in this Domain
{% for hostname, dnsattr in DC2.iteritems() %}
{{hostname}}.example.com. IN A {{dnsattr.ip}}
Run Code Online (Sandbox Code Playgroud)
角色/ DNS /任务/ main.yml:
- name: Update DNS zone file db.example.com
template:
src: db.example.com.j2
dest: "/tmp/db.example.com"
with_items: "{{DC1,DC2}}"
- name: Restart DNS Server
service:
name: named
state: restarted
Run Code Online (Sandbox Code Playgroud)
DNS区域文件已正确创建,但IP未按数字排序.我试过使用以下但没有运气:
按字母顺序对主机名进行排序
{% for hostname, dnsattr in center.iteritems() | sort %}
Run Code Online (Sandbox Code Playgroud)
找不到属性dnsattr
{% for hostname, dnsattr in center.iteritems() | sort(attribute='dnsattr.ip') %}
Run Code Online (Sandbox Code Playgroud)
找不到属性ip
{% for hostname, dnsattr in center.iteritems() | sort(attribute='ip') %}
Run Code Online (Sandbox Code Playgroud)
要对 IP 进行数字排序,您可以实现并使用您自己的过滤器插件(顺便说一句,我对任何其他解决方案感兴趣):
在ansible.cfg添加filter_plugins = path/to/filter_plugins.
在path/to/filter_plugins/ip_filters.py:
#!/usr/bin/python
def ip_sort(ip1, ip2):
# Sort on the last number
return int(ip1.split('.')[-1]) - int(ip2.split('.')[-1])
class FilterModule(object):
def filters(self):
return {
'sort_ip_filter': self.sort_ip_filter,
}
def sort_ip_filter(self, ip_list):
return sorted(ip_list, cmp=ip_sort)
Run Code Online (Sandbox Code Playgroud)
然后,在 Ansible 中:
- name: "Sort ips"
debug:
msg: vars='{{ my_ips | sort_ip_filter }}'
Run Code Online (Sandbox Code Playgroud)
我还会使用ipaddr过滤器来确保格式正确:
- name: "Sort ips"
debug:
msg: vars='{{ my_ips | ipaddr | sort_ip_filter }}'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
757 次 |
| 最近记录: |