Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't compare attribute to a number. Error: "not supported between instances of 'AnsibleUnsafeText' and 'int'"

Tags:

ansible

jinja2

- getent:
    database: passwd
- debug: 
    var: getent_passwd | dict2items | selectattr('value.1', '>=', 1000) | map(attribute='key') | list

And output is

TASK [debug] ******************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on 
({{getent_passwd | dict2items | selectattr('value.1', '>=', 1000) | map(attribute='key') | list}}): 
'>=' not supported between instances of 'AnsibleUnsafeText' and 'int'"}

How can I change 'value.1' to integer?

like image 383
Theppasin Kongsakda Avatar asked Dec 19 '25 07:12

Theppasin Kongsakda


1 Answers

Q: "How can I change value.1 to an integer?"

A: Use json_query function to_number. For example

    - debug:
        var: getent_passwd|
             dict2items|
             json_query('[?to_number(value[1]) >= `1000`].key')

Q: "How can I change 1000 into a variable?"

A: The substitution should be converted to a number too. It's a good idea to declare the query separately. For example

    - set_fact:
        myusers: "{{ getent_passwd|dict2items|json_query(query) }}"
      vars:
        myuid: 1000
        query: "[?to_number(value[1]) >= to_number('{{ myuid }}')].key"

Q: "How can I add more conditions into json_query function? Like selectattr('value.5', 'ne', '/sbin/nologin')."

A: Use pipe or and-expression. For example

    - getent:
        database: passwd
    - set_fact:
        myusers: "{{ getent_passwd|dict2items|json_query(query) }}"
      vars:
        myuid: 1000
        myshell: /usr/sbin/nologin
        query: "[?to_number(value[1]) >= to_number('{{ myuid }}')] |
                [?value[5] == '{{ myshell }}'].{user: key, uid: value[1], shell: value[5]}"
    - debug:
        var: myusers

give

    "myusers": [
        {
            "user": "libvirt-qemu", 
            "shell": "/usr/sbin/nologin", 
            "uid": "64055"
        }, 
        {
            "user": "nobody", 
            "shell": "/usr/sbin/nologin", 
            "uid": "65534"
        }
    ]

Fit the variables and the Comparison Operator to your needs.

The pipe in json_query might be considered an anti-pattern. Therefore and-expression should be used instead of the pipe. For example

  query: "[?(to_number(value[1]) >= to_number('{{ myuid }}')) &&
            (value[5] == '{{ myshell }}')].{user: key, uid: value[1], shell: value[5]}"
like image 132
Vladimir Botka Avatar answered Dec 21 '25 03:12

Vladimir Botka