Ansible 为什么寄存器在条件为false时仍在注册模块?

Ansible 为什么寄存器在条件为false时仍在注册模块?,ansible,Ansible,我有一个任务文件,该文件将获得容器名,该容器已装入特定的卷。结果存储在container_id变量中。此任务文件需要在linux和windows中执行。所以我添加了条件执行,但是“register”变量的行为很奇怪 - name: Get the container ID for volume "{{vol}}" mounted shell: "docker ps -a -q --filter volume={{vol}}" register: container_id when:

我有一个任务文件,该文件将获得容器名,该容器已装入特定的卷。结果存储在container_id变量中。此任务文件需要在linux和windows中执行。所以我添加了条件执行,但是“register”变量的行为很奇怪

- name: Get the container ID for volume "{{vol}}" mounted
  shell: "docker ps -a -q --filter volume={{vol}}"
  register: container_id
  when: ansible_os_family != "Windows"

- name: Get the container ID for volume "{{vol}}" mounted
  win_shell: "docker ps -a -q --filter volume={{vol}}"
  register: container_id
  when: ansible_os_family == "Windows"

- debug:
    var: container_id
当我在linux节点中运行这个程序时,我想它会在container_id变量中获得所有容器名称。但令我惊讶的是,结果是

ok: [remotenode] => {
    "container_id": {
        "changed": false,
        "skip_reason": "Conditional result was False",
        "skipped": true
    }
}
这意味着从windows模块跳过的输出已注册到容器id变量中

然后,我将调试放在linux模块下面,如下所示,这确保了此时的寄存器具有适当的值

- name: Get the container ID for volume "{{vol}}" mounted
  shell: "docker ps -a -q --filter volume={{vol}}"
  register: container_id
  when: ansible_os_family != "Windows"    

- debug:
    var: container_id

- name: Get the container ID for volume "{{vol}}" mounted
  win_shell: "docker ps -a -q --filter volume={{vol}}"
  register: container_id
  when: ansible_os_family == "Windows"
输出如下所示

ok: [remotenode] => {
    "container_id": {
        "changed": true,
        "cmd": "docker ps -a -q --filter volume=origvolfd48c6",
        "delta": "0:00:00.036279",
        "end": "2019-07-30 02:32:13.203036",
        "failed": false,
        "rc": 0,
        "start": "2019-07-30 02:32:13.166757",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "fb81938cdbbe",
        "stdout_lines": [
            "fb81938cdbbe"
        ]
    }
}
因此,即使跳过模块,寄存器也有值。为什么它会这样。有什么解决方法吗?

如果您查看,您将看到以下注释:

如果任务失败或被跳过,变量仍将以失败或跳过状态注册,避免注册变量的唯一方法是使用标记

所以发生在你身上的是Ansible的默认行为。您可以修改
playbook
以使用如下标记:

- name: Get the container ID for volume "{{vol}}" mounted
  shell: "docker ps -a -q --filter volume={{vol}}"
  register: container_id
  tags:
    - linux

- name: Get the container ID for volume "{{vol}}" mounted
  win_shell: "docker ps -a -q --filter volume={{vol}}"
  register: container_id
  tags:
    - windows

- debug:
    var: container_id
然后可以使用
--tags
--skip tags
选项运行它