Ansible 测试变量以什么开头

Ken*_*ney 2 ansible

我需要能够安装一个 MySQL 库。Python 有 1 个用于 v2 的包和另一个用于 v3 的包。我需要能够告诉 Ansible 安装哪个包。

- name: Ensure MySQL-python is installed
  pip:
    name: MySQL-python
    state: present
  become: true
  when: python_version is regex("^2.*")

- name: Ensure mysqlclient is installed
  pip:
    name: mysqlclient
    state: present
  become: true
  when: python_version is regex("^3.*")
Run Code Online (Sandbox Code Playgroud)

正则表达式是有效的,但 Ansible 正在跳过它们,即使这样:

- debug:
    var: python_version
Run Code Online (Sandbox Code Playgroud)

返回这个:

TASK [debug] ****************************************************************************************************************************************************************
ok: [localhost] => {
    "python_version": "2.7.10"
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*tka 5

正则表达式适用于 ansible 2.7.9。下面的例子

      vars:
        python_version: "2.7.10"
      tasks:
        - debug:
            msg: Python version 2
          when: python_version is regex('^2.*')
Run Code Online (Sandbox Code Playgroud)

    "msg": "Python version 2"
Run Code Online (Sandbox Code Playgroud)

对于复杂的测试,版本比较更方便。下面的例子给出了相同的结果。

        - debug:
            msg: Python version 2
          when:
            - python_version is version('2', '>=')
            - python_version is version('3', '<')
Run Code Online (Sandbox Code Playgroud)

该测试首次regex记录在Ansible 2.8中。在早期版本中,只有测试searchmatch文档。在当前源中,测试searchmatch实现是在regex

    def match(value, pattern='', ignorecase=False, multiline=False):
        return regex(value, pattern, ignorecase, multiline, 'match')

    def search(value, pattern='', ignorecase=False, multiline=False):
    ?    return regex(value, pattern, ignorecase, multiline, 'search')
Run Code Online (Sandbox Code Playgroud)

  • OP 示例中的正则表达式对我来说正确匹配并且正在完成这项工作(ansible 2.8.1)。所以我怀疑问题出在其他地方。同时,我完全同意版本比较是这种情况下的良好实践解决方案。 (2认同)