1

I have this simple Ansible task:

- name: read file
  shell: cat "{{ '/home/myhome/confiles/file.txt' }}"
  register: config

- name: set regex for myvar 
  ansible.builtin.set_fact:
    myvar: |-
      {{
          config.stdout |
          regex_search('^number *= *.*', multiline=True) |
          regex_replace('.*= *(.*)$', '\1')
      }}

- name: debug myvar
  ansible.builtin.debug:
    msg:
      - myvar ---> {{ myvar }}
      - myvar ---> {{ myvar | type_debug }}
      - myvar ---> {{ myvar | int }}
      - myvar ---> {{ myvar |int | type_debug }}

that return this:

TASK [query : debug myvar] **********
ok: [127.0.0.1] => {
    "msg": [
        "myvar ---> '5002'",
        "myvar ---> AnsibleUnsafeText",
        "myvar ---> 0",
        "myvar ---> int"
    ]
}

Expected result is:

"myvar ---> 5002"

Actual result is:

"myvar ---> 0"

Where is the problem? Why this behaviour?

U880D
  • 8,601
  • 6
  • 24
  • 40
ferdinand
  • 21
  • 3

1 Answers1

0

Because my_var is '5002', quotes included

You can either adjust the regex and as already mentioned within the comments by β.εηοιτ.βε, or strip the quotes from your variable by using slice notation or a Custom Filter Plugin.

{{ myvar[1:-1] | int }}

Thanks to

U880D
  • 8,601
  • 6
  • 24
  • 40