2

在这里,我有一个关于如何使用 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文件,但它看起来像一个结构化文件。想象一下,我想找到一种方法来获取interfaces->vme->unit 0->family inetAnsible 剧本中的价值,我该怎么做?我可以在 Ansible 中使用哪个解析器?

我已经阅读了此页面,但我真的不知道要使用哪个解析器以及如何使用它:https ://docs.ansible.com/ansible/latest/network/user_guide/cli_parsing.html

谢谢,马克斯

4

1 回答 1

1

关于你的问题

我可以在 Ansible 中使用哪个解析器?

如果您无法在 ( show config | display json) 之前以 JSON 结构化格式导出配置,因为它在示例中不受您的控制,您可能需要处理给定的结构。

这是一个.conf文件,但它看起来像一个结构化文件。

由于该结构看起来不像Parsing semi-structured text with Ansible中的可用模板之一,因此您可能需要寻找其他选项。

我假设您不想通过file_lookup模块读取整个文件并在 Ansible 中完全解析它。

查找插件似乎也没有实现提供的结构。INI 查找似乎也不合适。

想象一下,我想找到一种方法来获取interfaces->vme->unit 0->family inetAnsible 剧本中的价值,我该怎么做?

如果您的配置文件只有那个结构并且它没有改变,我们不知道

...实际上它的方式更长...

以下方法可能会奏效一段时间:

- 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

还可以选择编写自己的自定义插件。

谢谢

来自评论的链接

于 2021-06-01T08:12:32.430 回答