我需要在/etc/bind/example.com路径下的绑定文件中使用jinja2增加序列号。
以此为例:
$TTL 86400
@ 3600 IN SOA example.server.com. hostmaster.example.it. (
2019290603 ; Serial
////////////////////
我想要这个:
2019290604 ; Serial
或
2019290700 ; Serial
我需要 jinja2,因为我将使用 Ansible 将其自动化。
我该怎么做?
下面的任务可以完成这项工作。
vars:
next_serial: '2019290604'
tasks:
- lineinfile:
path: /etc/bind/example.com
regexp: '(?!.*{{ next_serial }}.*)^(\s*)(\s\d*)(\s*;\s*Serial.*)$'
line: '\1 {{ next_serial }}\3'
backrefs: yes
regexp 首先向前查看并仅在 next_serial 不存在时匹配该行。这使得任务幂等。
与数字(\s\d*)匹配的组故意占用一个空格,并使第一组缩短一个空格。 “line: ' {{ ...” 通过分隔第一组和变量 {{ next_serial }} 的扩展来添加空格。由于某种原因“{{next_serial}}”无法按预期工作。
解决了相关问题 - 在单个区域文件中更新 SOA 的序列。该序列遵循 RFC 1912,我使用的是 Ansible 替换模块。假设:序列号是唯一的 10 位数字,并且在整个文件中是唯一的。
- name: get zone file from remote for inspection
register: result
slurp:
src: "/var/named/{{ base_domain }}.zone"
- name: update SOA serial in remote zone file
vars:
gen_serial: "{{ lookup('pipe','date +%Y%m%d01') | int }}"
old_serial: "{{ result['content'] | b64decode | regex_findall('\\d{10}') | first | int }}"
new_serial: "{% if gen_serial < old_serial %}{{ 1 + old_serial | int }}{% else %}{{ gen_serial }}{% endif %}"
replace:
regexp: "\\b{{ old_serial }}\\b"
replace: "{{ new_serial }}"
path: "/var/named/{{ base_domain }}.zone"