如果多行寄存器中不存在字符串,则执行 ansible 任务

如果多行寄存器中不存在字符串,则执行 ansible 任务

我只想在缺少配置时推送网络设备的配置,通过在注册表输出中搜索字符串,首先我运行此任务来记录目标设备上的运行配置:

  # Collect information about the available configuration
- name: Execute show command
  cisco.ios.ios_command:
    commands: 
    - show runn | in repository ## to find if the repository is already configured
  register: output

我想使用输出寄存器有条件地运行以下任务:

- name: Push repository configuration
  cisco.ios.ios_command:
    commands:
    - conf t
    - repository MAIN
    - url ftp://{{ repository_main }}
    - user {{ repository_main_user}} password plain {{ repository_main_password }}
    - exit
    - repository SECONDARY
    - url ftp://{{ repository_sec }}/
    - user {{ repository_sec_user}} password plain {{ repository_sec_password }}
    - end
  when: 'not "MAIN" in {{ output.stdout }} and not "SECONDARY" in {{ output.stdout }}'

这是output.stdout 的样子:

TASK [print output] ************************************************************
Saturday 19 November 2022  06:45:44 +0000 (0:00:06.370)       0:00:06.409 ***** 
ok: [node1] => 
  msg:
  - |-
    repository MAIN
    --
    repository SECONDARY

当我检查网络设备上 ansible 用户的会话时,我发现它再次配置了存储库,这不是我想要的,我该如何控制它?事实上,stdout 是多行输出的一个因素吗?

答案1

修复条件

      when:
        - "'MAIN' not in output.stdout"
        - "'SECONDARY' not in output.stdout"

测试一下

- hosts: localhost

  tasks:

    - debug:
        msg: OK
      when:
        - "'MAIN' not in output.stdout"
        - "'SECONDARY' not in output.stdout"
      vars:
        output:
          stdout: XY

    - debug:
        msg: OK
      when:
        - "'MAIN' not in output.stdout"
        - "'SECONDARY' not in output.stdout"
      vars:
        output:
          stdout: XY MAIN

    - debug:
        msg: OK
      when:
        - "'MAIN' not in output.stdout"
        - "'SECONDARY' not in output.stdout"
      vars:
        output:
          stdout: XY SECONDARY

给出

PLAY [localhost] *****************************************************************************

TASK [debug] *********************************************************************************
ok: [localhost] => 
  msg: OK

TASK [debug] *********************************************************************************
skipping: [localhost]

TASK [debug] *********************************************************************************
skipping: [localhost]

PLAY RECAP ***********************************************************************************
localhost: ok=1    changed=0    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0

相关内容