首页 > 解决方案 > 如何在模块中使用 return 'stdout'

问题描述

如何使用until模块返回的数据ios_module?我需要找到可以通过的最大传输单元(MTU)。如果数据包通过,输出将有“!!!!!!”。

- name: Test mtu size
  ios_command:
    commands:
      - command: 'ping 10.10.10.10 df-bit size {{ pkt_size + 5 }}  repeat 4'
    provider: "{{ cli }}"          
  register: dump
  until: '"!!!!" in stdout'

标签: ansible

解决方案


根据文档重试任务直到满足条件,您似乎缺少示例中提到的一些参数。你可以尝试像这样的测试

---
- hosts: localhost
  become: no
  gather_facts: no

  vars:

    PING_COUNT: "3"

  tasks:

  - name: Ping until
    shell:
      cmd: ping -c {{ PING_COUNT }} $(hostname)
    register: result
    until: result.stdout.find("icmp_seq=4") != -1
    retries: 5
    delay: 2

  - name: Show result
    debug:
      msg: "{{ result.stdout }}"

这对于 a 会失败,PING_COUNT: "3"但对于 a 会成功PING_COUNT: "5"

在内部任务命令中使用外部任务计数器是行不通的attempts

  - name: Ping until
    shell:
      cmd: ping -c {{ result.attempts | default('1') }} $(hostname)
    register: result
    until: result.stdout.find("icmp_seq=4") != -1
    retries: 5
    delay: 2

该作业将使用初始计数器进行编译并保留该值,执行将导致

TASK [Echo until] ******************************************************************
fatal: [localhost]: FAILED! => changed=true
  attempts: 5
  cmd: ping -c 1 $(hostname)
  ...
  stdout: |-
    PING test.example.com (93.184.216.34) 56(84) bytes of data.
    64 bytes from test.example.com (93.184.216.34): icmp_seq=1 ttl=64 time=0.022 ms

    --- test.example.com ping statistics ---
    1 packets transmitted, 1 received, 0% packet loss, time 0ms
  ...

如果有必要在命令中计数,则以下方法可能会有所帮助。

  - name: Ping until
    shell:
      cmd: ping -c {{ item }}  $(hostname)
    register: result
    with_sequence:
      - "1-5"
    until: result.stdout.find("icmp_seq=4") != -1
    retries: 1

推荐阅读