ansibleansible-2.xansible-inventoryansible-factsansible-awx

compare value with list of int in ansible


Want to compare values with list for int and display msg values greater than 15

  tasks:

    - name: Create a List variable and print it
      set_fact:
        Continents: ["10","20"]
    - name: set fatc
      set_fact:
         int_list: "{{ Continents|map('int')|list }}"
    - debug:
        msg: "{{greater than 15}}"
      when: "{{int_list}}" > 15

Getting error as below:

The offending line appears to be:

        msg: "{{ list }}"
      when: "{{int_list}}" > 15
                             ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
    with_items:
      - {{ foo }}
Should be written as:
    with_items:
      - "{{ foo }}"

Expected Output:

greater than 15

Solution

  • You can achieve the same with two tasks. Change your list to integers. Make the debug task to loop through the Continents variable.

    - hosts: localhost
      tasks:
        - name: Create a variable with a list of integers
          set_fact:
            Continents: [10, 20]
    
        - debug:
            msg: "greater than 15"
          loop: "{{ Continents }}"
          when: item > 15  ##item becomes each value of the Continents variable. So, 10, 20 and so on. 
    

    Gives:

    skipping: [localhost] => (item=10)
    ok: [localhost] => (item=20) => {
         "msg": "greater than 15"
    }