晚上好。
我正在 Ansible 中编译生成 host_vars 文件。
输入端有一个“原始”文件,其中包含未来的主机地址(将根据模板生成 /etc/network/interface 文件),掩码始终为常量 - 255.255.255.128,以及网关 - *. *.*.1
host_vars.yml.j2
---
sys_hostname: "{{ cfg_hostname }}"
sys_type: "{{ type }}"
sys_eth0_ipv4_address: "{{ tb_eth0 }}"
sys_eth0_ipv4_gateway: "{{ tb_eth0_gw }}"
sys_eth0_ipv4_netmask: "255.255.255.128"
原始值文件:
raw_host_vars
ES:TB-MT:SiteHostName-1:10.58.11.111
ES:TB-MT:SiteHostName-2:10.58.12.111
ES:TB-MT:SiteHostName-3:10.58.13.111
生成文件的脚本
#!/usr/bin/env python3
import os
import sys
import yaml
import ipaddress
from jinja2 import Environment, FileSystemLoader, Template
ENV = Environment(loader=FileSystemLoader('./templates'))
with open('./raw_host_vars') as file:
raw_host_vars = file.read().split("\n")
template = ENV.get_template("host_vars.yml.j2")
for line in raw_host_vars:
iso = line.split(":")[0]
type = line.split(":")[1]
cfg_hostname = line.split(":")[2]
tb_eth0 = line.split(":")[3]
tb_eth0_gw = # Нужно сформировать гейтвей по шаблону \*.\*.\*.1
# изменить только последний октет
print(template.render(cfg_hostname=cfg_hostname,
iso=iso,
type=type,
tb_eth0=tb_eth0,
tb_eth0_gw=tb_eth0_gw))
# End of script
如何使用ipaddress模块从有关子网的可用数据和主机本身的地址生成新地址(网关) (文档几乎不包含示例)?
工作技巧:
tb_eth0_gw = ".".join(line.split(":")[2].split(".")[:3])+".1",
如果网关是子网上的第一个地址: