首页 > 解决方案 > 如何在条件评估时查看 Ansible

问题描述

我正在尝试使用 Ansible 升级 Cisco 路由器,并在我实际重新启动之前使用 cli_config 模块检查引导标记是否设置正确。

我正在尝试使用 when 子句来防止剧本应用更改,除非配置看起来正确

我想确保变量“文件名” - 这是管理员传递给剧本的图像的名称 - 包含在检查引导文件的命令的输出中 - 该命令已注册到名为“boot_sys_marker_running_config”的变量"

我已经尝试过:

when: filename in boot_sys_marker_running_config.stdout

我也试过

when: filename == "boot_sys_marker_running_config.stdout"

在运行剧本和剧本中的集合时,我尝试使用 -vvvv 选项调试这些,debugger: always但没有洞察力

我似乎总是知道条件不成功 - 但我看不到条件认为我希望它评估什么 - 有谁知道如何“调查”条件以便我可以适当地修改它?

剧本选项:

-e "filename=csr1000v-universalk9azn.16.11.01b.SPA.bin"

我注册变量并尝试使用条件的剧本的一部分

- name: check to see that the correct boot system marker has been configured   
  cli_command:
    command: "show run | i boot system"   
  register: boot_sys_marker_running_config   ignore_errors: yes
- name: copy running config to startup when boot marker is correct   
  cli_command:
    command: "copy running-config startup-config"   
  register: writing_config_to_startup
  ignore_errors: yes
  when: filename in boot_sys_marker_running_config.stdout

我有一个调试任务来显示 boot_sys_marker_running_config 的内容:

TASK [debug] ************************************************************************************************************************************************
ok: [r3-cvpn1.corp.ncsc.gov.uk] => {
    "msg": {
        "changed": false,
        "failed": false,
        "stdout": "boot system bootflash:csr1000v-universalk9azn.16.11.01b.SPA/packages.conf",
        "stdout_lines": [
            "boot system bootflash:csr1000v-universalk9azn.16.11.01b.SPA/packages.conf"
        ]
    }
}

标签: ansiblejinja2

解决方案


.bin文件名中删除挂起的。字符串中缺少此扩展名stdout

-e "filename=csr1000v-universalk9azn.16.11.01b.SPA.bin"

正确的

-e "filename=csr1000v-universalk9azn.16.11.01b.SPA"

正确的条件应该是

when: boot_sys_marker_running_config.stdout is search(filename)

下面的测试按预期工作。

- hosts: localhost
  vars:
    filename: 'csr1000v-universalk9azn.16.11.01b.SPA'
    stdout: 'boot system bootflash:csr1000v-universalk9azn.16.11.01b.SPA/packages.conf'
  tasks:
    - debug:
        msg: filename found
      when: stdout is search(filename)

推荐阅读