Registered fact does not work in “when” condition

2019-07-31 18:56发布

问题:

I have my playbook as below:

---
- hosts: myser
  tasks:
  - name: Checking.
    win_command: mycommand
    register: win_command_result

  - set_fact:
      myvar={{win_command_result.stdout | regex_search('\\d+')}}
    register: myvar_result

  - debug:
      var: myvar_result.ansible_facts.ple

  - name: Checking Condition
    win_command: ipconfig
    register: ipconfig
    when: myvar_result.ansible_facts.ple < 5000

  - debug:
      var: ipconfig

And below is output.

I am getting two different values per server but the task Checking Condition gets skipped. Based on the value, for one server it should skip and for another it should execute.

PLAY [myser] 
*******************************************************

TASK [Gathering Facts] 
**************************************************
ok: [ser1]
ok: [ser2]

TASK [Checking] 
****************************
changed: [ser1]
changed: [ser2]

TASK [set_fact] 
*********************************************************
ok: [ser1]
ok: [ser2]

TASK [debug] 
************************************************************
ok: [ser1] => {
    "myvar_result.ansible_facts.ple": "232"
}
ok: [ser2] => {
    "myvar_result.ansible_facts.ple": "378416"
}

TASK [Checking Condition] 
**********************************************
skipping: [ser1]
skipping: [ser2]

TASK [debug] 
************************************************************
ok: [ser1] => {
    "ipconfig": {
        "changed": false, 
        "skip_reason": "Conditional result was False", 
        "skipped": true
    }
}
ok: [ser2] => {
    "ipconfig": {
        "changed": false, 
        "skip_reason": "Conditional result was False", 
        "skipped": true
    }
}

PLAY RECAP 
**************************************************************
ser2 : ok=5    changed=1    unreachable=0    failed=0   
ser1 : ok=5    changed=1    unreachable=0    failed=0   

I want to use myvar_result.ansible_facts.ple in when condition. So idea here is if myvar_result.ansible_facts.ple crosses value of 5000 then execute "checking name"

Am I missing something here? How to get it work?

回答1:

It is working properly, but you are comparing a string with an integer.

As you can see in your output:

"myvar_result.ansible_facts.ple": "232"
"myvar_result.ansible_facts.ple": "378416"

your values are strings (as is any command result passed in stdout, as well as the output of the regex_search filter).


Cast them to integer before doing the comparison in the conditional:

- name: Checking Condition
  win_command: ipconfig
  register: ipconfig
  when: myvar_result.ansible_facts.ple|int < 5000


标签: ansible