【问题标题】:How to split in ansible如何在ansible中拆分
【发布时间】:2020-04-02 16:25:09
【问题描述】:

我对 ansible 比较陌生,但我正在尝试将我的一些 python 脚本转换为 ansible 剧本,并且很难理解如何分配变量然后循环。我有一本运行 show vlan brief 的剧本:

---
- name: Get ARP information
  hosts: all
  gather_facts: false


  tasks:
    - name: show vlan brief
      raw: "show vlan brief | i test"
      register: vlan_output

    - debug: var=vlan_output.stdout_lines

这给出了以下输出:

PLAY [Get ARP information] *****************************************************

TASK [show vlan brief] *********************************************************
changed: [sw1]

TASK [debug] *******************************************************************
ok: [sw1] => {
    "vlan_output.stdout_lines": [
        "100  test                             active    Gi0/3, Gi0/1, Gi0/2",
        "101  test2                            active    "
    ]
}

PLAY RECAP *********************************************************************
sw1                        : ok=2    changed=1    unreachable=0    failed=0

我只想获取vlan号,在这种情况下是100和101,然后循环执行“show mac address table | inc VLAN_NUM”

我尝试在注册和调试行中添加拆分,但不断收到错误消息:

#split added
- debug: var=vlan_output.stdout_lines.split(' ')

#return error
"vlan_output.stdout_lines.split(\" \")": "VARIABLE IS NOT DEFINED!"

在 python 中,我将遍历项目并拆分字符串以获得我需要的内容。在 ansible 中,该过程的首选或等效是什么?

【问题讨论】:

    标签: split ansible


    【解决方案1】:

    问:Run command:

    "show mac address-table | include <VLAN_NUMBER>"
    

    试试这个

        - set_fact:
            my_vlan_numbers: "{{ vlan_output.stdout_lines|
                                 map('regex_replace', myregex, myreplace)|
                                 list }}"
          vars:
            myregex: '^(\S*) (.*)$'
            myreplace: '\1'
        - shell:
            cmd: "show mac address-table | include {{ item }}"
          loop: "{{ my_vlan_numbers }}"
    


    myregex 的详细信息
    ^ ..... match beginning of the line
    (\S*) . first group of any non-space chars
          . match space
    (.*) .. second group of any chars
    $ ..... match end of the line
    

    replace

    的详细信息
    \1 .... backreference the first group of myregex
    

    【讨论】:

    • 那行得通,但我一生都无法弄清楚如何/为什么.....有任何好的链接可以解释该过程吗?
    • 参见 Python 正则表达式。例如docs.python.org/3/howto/regex.html
    • 然后我将如何在我的剧本的其他部分使用该变量。例如,下一步是运行“show mac address-table | include ”。
    • 感谢您更新答案以显示如何在调试下分配 my_vlan_numbers。
    • 查看更新后的答案。如果有的话,打开一个新问题。
    猜你喜欢
    • 1970-01-01
    • 2022-11-20
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-03-12
    相关资源
    最近更新 更多