user2363318
user2363318

Reputation: 1067

ansible parse extra var use default if regex fails

I have the following code which isn't throwing an error but the fact is empty

  - shell: echo '{{ p }}'
    register: results

  - debug:
      var: results

  - set_fact:
      myrepo: "{{ results.stdout | regex_search(regexp,'\\1') | default ( {'0':'global'} ) }}"
    vars:
      regexp: '(.*)/(.*)'

Here is the output

TASK [command] **************************************************************************************************************************************************************************************
changed: [localhost]

TASK [debug] ****************************************************************************************************************************************************************************************
ok: [localhost] => {
    "results": {
        "changed": true, 
        "cmd": "echo 'tim'", 
        "delta": "0:00:00.095831", 
        "end": "2017-09-06 16:37:19.977023", 
        "rc": 0, 
        "start": "2017-09-06 16:37:19.881192", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "tim", 
        "stdout_lines": [
            "tim"
        ]
    }
}

TASK [set_fact] *************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] ****************************************************************************************************************************************************************************************
ok: [localhost] => {
    "myrepo": ""
}

The command is ansible-playbook -i hosts -c local file.yml --extra-vars "p=tim" I want myrepo to be global if the regex results are empty

Upvotes: 1

Views: 1726

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

Without any parameters default filter is triggered only when value is Undefined. But result of unmatched regexp is an empty string, which is not Undefined. You may want to set boolean flag:

  - set_fact:
      myrepo: "{{ results.stdout | regex_search(regexp,'\\1') | default('global', boolean=True) }}"
    vars:
      regexp: '(.*)/(.*)'

Upvotes: 2

Related Questions