Check if a list contains an item in Ansible

2020-08-09 04:54发布

问题:

I'm trying to check if the version supplied is a valid supported version. I've set the list of acceptable versions in a variable, and I want to fail out of the task if the supplied version is not in the list. However, I'm unsure of how to do that.

#/role/vars/main.yml
---
  acceptable_versions: [2, 3, 4]

and

#/role/tasks/main.yml
---
  - fail: 
      msg: "unsupported version"
      with_items: "{{acceptable_versions}}"
      when: "{{item}} != {{version}}"

  - name: continue with rest of tasks...

Above is sort of what I want to do, but I haven't been able to figure out if there's a one line way to construct a "list contains" call for the fail module.

回答1:

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions


回答2:

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested



标签: yaml ansible