如何解决使用 Ansible 在结构化文件中查找值
这里我有一个关于如何使用 Ansible 在结构化文件中查找值的小问题。我看过 lineinfile 但我不太确定它会有所帮助。如果我们假设我的文件看起来像这样(实际上它要长得多,但出于明显的原因,我不能在这里发布它^^)
################## junos.conf ##################
system {
auto-snapshot;
root-authentication {
encrypted-password ## SECRET-DATA
}
services {
ssh;
netconf ssh;
scp;
}
syslog {
user * {
any emergency;
}
file messages {
any notice;
authorization info;
}
file interactive-commands {
interactive-commands any;
}
}
processes {
dhcp-service {
traceoptions {
file dhcp_logfile size 10m;
level all;
flag all;
}
}
}
}
interfaces {
irb {
unit 0 {
family inet {
dhcp {
vendor-id Juniper-ex4300-48t;
}
}
}
}
vme {
unit 0 {
family inet {
address 172.0.0.1/24
}
}
}
}
forwarding-options {
storm-control-profiles default {
all;
}
}
vlans {
default {
vlan-id 1;
l3-interface irb.0;
}
}
这是一个 .conf
文件,但它看起来像一个结构化文件。想象一下,我想找到一种方法来获取 Ansible 剧本中的 interfaces->vme->unit 0->family inet
值,我该怎么做?我可以在 Ansible 中使用哪个解析器?
我已经阅读了这个页面,但我真的不知道该使用哪个解析器以及如何使用它:https://docs.ansible.com/ansible/latest/network/user_guide/cli_parsing.html
谢谢, 最大
解决方法
关于你的问题
我可以在 Ansible 中使用哪个解析器?
如果您在 (show config | display json
) 之前无法以 JSON 结构化格式导出配置,因为它在示例中不受您的控制,您可能需要处理给定的结构。
这是一个 .conf
文件,但它看起来像一个结构化文件。
由于结构看起来不像 Parsing semi-structured text with Ansible 中的可用模板之一,您可能需要寻找其他选项。
我假设您不想通过 file_lookup 模块读取整个文件并在 Ansible 中完全解析它。
Lookup Plugins 似乎也没有实现所提供的结构。 INI lookup 似乎也不合适。
想象一下,我想找到一种方法来获取 Ansible 剧本中的 interfaces->vme->unit 0->family inet
值,我该怎么做?
如果你的配置文件只有那个结构并且没有改变,我们不知道
...实际上它的方式更长...
以下方法可能会奏效一段时间:
- name: Read IP address from Junos config file
shell:
cmd: grep -o "address.*" /tmp/junos.conf | cut -f 2 -d " " | cut -f 1 -d "/"
register: ip_address
warn: false
check_mode: false
changed_when: false
delegate_to: localhost
tags: junos_conf
- name: Show IP address
debug:
msg: "{{ ip_address }}"
tags: junos_conf
还可以选择编写自己的自定义插件。
感谢
来自评论的链接
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。