首页 > 解决方案 > Ansible: when variable/fact is greater than or equal to AND less than or equal to?

问题描述

As the question implies, I'm trying to evaluate a fact in an Ansible role if the value is greater than or equal to a number AND less than or equal to another number; basically a range. I can't seem to find how to do this.

Here's part of my playbook snippet:

- name: DEBUG Snapshots to be deleted
  debug:
    msg: The snapshot for {{ inventory_hostname.split("_")[0] }} is {{ snap_age }} day(s) old and would have been deleted.
  when: (old_snap is defined) and (old_snap == true) and (snap_age >= "1")

This code above actually works, and it returns two items, one that is 80 days old and one that is 102 days old.

Now I want to get any snapshots that are between 1 and 100 in age. I tried doing this:

- name: DEBUG Snapshots to be deleted
  debug:
    msg: The snapshot for {{ inventory_hostname.split("_")[0] }} is {{ snap_age }} day(s) old and would have been deleted.
  when: (old_snap is defined) and (old_snap == true) and (snap_age >= "1" and snap_age <= "100")

But that didn't work. I then tried:

- name: DEBUG Snapshots to be deleted
  debug:
    msg: The snapshot for {{ inventory_hostname.split("_")[0] }} is {{ snap_age }} day(s) old and would have been deleted.
  when: (old_snap is defined) and (old_snap == true) and ((snap_age >= "1" and snap_age <= "100"))

That didn't work either, so I'm wondering what I'm doing wrong here. It must be something I'm overlooking.

标签: ansibleansible-facts

解决方案


This is because you're not using integers but strings.

This playbook not work :

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    old_snap: true
  tasks:
  - name: DEBUG Snapshots to be deleted
    debug:
      msg: The snapshot for {{ inventory_hostname.split("_")[0] }} is {{ item }} day(s) old and would have been deleted.
    when: (old_snap is defined) and (old_snap == true) and (item >= "1" and item <= "100")
    with_items:
    - "80"
    - "102"

But this one works :

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    old_snap: true
  tasks:
  - name: DEBUG Snapshots to be deleted
    debug:
      msg: The snapshot for {{ inventory_hostname.split("_")[0] }} is {{ item }} day(s) old and would have been deleted.
    when: (old_snap is defined) and (old_snap == true) and (item >= 1 and item <= 100)
    with_items:
    - 80
    - 102

If you can't use integers, you can pipe them with intfilter like :

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    old_snap: true
  tasks:
  - name: DEBUG Snapshots to be deleted
    debug:
      msg: The snapshot for {{ inventory_hostname.split("_")[0] }} is {{ item }} day(s) old and would have been deleted.
    when: (old_snap is defined) and (old_snap == true) and (item | int >= 1 and item | int <= 100)
    with_items:
    - "80"
    - "102"

I'm using ansible 2.8.7, command is ansible-playbook <your file>


推荐阅读