首页 > 解决方案 > 解析 ansible playbook 输出

问题描述

我的剧本如下


  - name: Juniper SRX Compliance checks
    hosts: juniper
    gather_facts: false
    tasks:
    - name: Syslog server check
      junos_config:
         src: /home/gefelas/ansible_junos/files/syslog_config.txt
      diff: true
      register: junos_output
    - debug:
        msg: Syslog server check - This check has failed with the following output({{ junos_output.diff.prepared }})
       when: junos_output.changed
    - debug:
        msg: Syslog server check - This check has passed with the following output({{ junos_output.diff.prepared }})
      when: not junos_output.changed

它产生输出(在 ansible.cfg 中使用 stdout_callback = community.general.yaml )

msg: |-
 Syslog server check - This check has failed with the following output([edit system syslog host 192.168.100.70]
+     interactive-commands any;
[edit system syslog host 192.168.100.70]
+    facility-override local1;
+    log-prefix firewall;
+    source-address 172.16.203.121;
+    explicit-priority;
[edit system syslog]
+    file messages {
+        any critical;
+        authorization info;
+    }
+    file default-log-messages {
+        structured-data;
+    }
+    file sessions {
+        user info;
+    }
+    file interactive-commands {
+        interactive-commands error;
+    })

什么正则表达式模块适合产生以下输出

msg: |-
   Syslog server check - This check has failed with the following output

    set system syslog archive size 300000
    set system syslog archive files 3
    set system syslog archive world-readable
    set system syslog user * any emergency
    set system syslog host 192.168.100.70 any any
    set system syslog host 192.168.100.70 interactive-commands any
    set system syslog host 192.168.100.70 facility-override local1
    set system syslog host 192.168.100.70 log-prefix firewall
    set system syslog host 192.168.100.70 source-address "172.16.203.121"
    set system syslog host 192.168.100.70 explicit-priority
    set system syslog file messages any critical
    set system syslog file messages authorization info
    set system syslog file default-log-messages structured-data
    set system syslog file sessions user info
    set system syslog file interactive-commands interactive-commands error

在剧本中添加类似的东西会有什么不同吗?

  - set_fact:  
     junos_output: |  
      {{ junos_output |  
      map('regex_replace','.*\\s+( )\\s+.*','\\g<ip>') |   
  list }}   
 

标签: parsingansible

解决方案


我给你我最好的技巧,在 Ansible 中以明文形式为路由器打印“设置”内容。它很脏并且破坏了抽象,但它非常方便,我仍然喜欢它。

- name: Print configuration
  delegate_to: localhost
  shell: "echo '{{ srx_config|join(cr) }}' > /dev/tty"
  when: ansible_verbosity > 0
  changed_when: false
  vars:
    cr: '{{ "\n" }}'

这里的主要技巧是使用/dev/ttyfor 输出。如果您使用 -v 选项运行 playbook,您会在屏幕上的 plantext 中获得来自 srx_config 的所有行,不带引号等。调试它所需要做的就是登录控制台并将它们粘贴到信息“配置”模式。


推荐阅读