我把真相的来源存储在yaml文件中
- Hostname: NY-SW1
IP mgmt address: 10.1.1.1
OS: IOS
Operational status: Install
Role of work: Switch
Site: New_York
- Hostname: MI-SW1
IP mgmt address: 11.1.1.1
OS: NX-OS
Operational status: Install
Role of work: Switch
Site: Maiami
- Hostname: PA-SW1
IP mgmt address: 12.1.1.1
OS: Arista
Operational status: Install
Role of work: Witch
Site: Paris我想通过python脚本从上面的文件中获得yaml ansible主机清单,如下所示:
hosts.yaml
---
new_york:
hosts:
ny-sw1:
ansible_host: 10.1.1.1
os: ios
'role of work': switch
maiami:
hosts:
mi-sw1:
ansible_host: 11.1.1.1
os: nxos
'role of work': switch
paris:
hosts:
pa-sw1:
ansible_host: 12.1.1.1
os: arista
'role of work': switch有人能给出建议吗--哪一种蟒蛇结构或氪石样本可以帮助员工实现自动化?
发布于 2022-05-18 21:38:41
例如,Ansible剧本
- hosts: localhost
tasks:
- set_fact:
sot: "{{ lookup('file', 'sot-inventory.yaml')|from_yaml }}"
- template:
src: hosts.yaml.j2
dest: hosts.yaml和模板
shell> cat hosts.yaml.j2
---
{% for i in sot|groupby('Site') %}
{{ i.0|lower }}:
hosts:
{% for j in i.1 %}
{{ j['Hostname']|lower }}:
ansible_host: {{ j['IP mgmt address'] }}
os: {{ j['OS']|lower }}
'role of work': {{ j['Role of work']|lower }}
{% endfor %}
{% endfor %}创建文件hosts.yaml
shell> cat hosts.yaml
---
maiami:
hosts:
mi-sw1:
ansible_host: 11.1.1.1
os: nx-os
'role of work': switch
new_york:
hosts:
ny-sw1:
ansible_host: 10.1.1.1
os: ios
'role of work': switch
paris:
hosts:
pa-sw1:
ansible_host: 12.1.1.1
os: arista
'role of work': witch试试看
shell> ansible-inventory -i hosts.yaml --list --yaml
all:
children:
maiami:
hosts:
mi-sw1:
ansible_host: 11.1.1.1
os: nx-os
role of work: switch
new_york:
hosts:
ny-sw1:
ansible_host: 10.1.1.1
os: ios
role of work: switch
paris:
hosts:
pa-sw1:
ansible_host: 12.1.1.1
os: arista
role of work: witch
ungrouped: {}发布于 2022-05-18 13:25:07
不同方式
用PyYaml解析YAML
用pip install pyyaml安装,然后
import yaml
with open("sot-inventory.yaml", "r") as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)Regex老派方法
您可以使用带有多个匹配和命名组的regex,并以所需格式打印输出。
示例:
r"- Hostname: (?P<hostname>.*)\n\s*IP mgmt address: (?P<ip>.*)\n"gm将创建3个匹配的两个组(组主机名和组IP)。
查看组如何工作:https://docs.python.org/3/howto/regex.html#grouping
你可以在这里试试你的正则表达式:https://regex101.com/r/7Gz3JQ/2
如果你被困在这里,不要犹豫粘贴你的脚本。我们会帮忙的。
https://stackoverflow.com/questions/72289828
复制相似问题