Ansible:如果变量以大写形式存储,如何条件运行?

Ansible: How to conditional run if variable is stored in uppercase?

提问人:uwe A 提问时间:11/15/2023 最后编辑:U880Duwe A 更新时间:11/16/2023 访问量:50

问:

我是 Ansible 的新手,并尝试在条件子句中运行步骤。 该变量使用 Oracle SQL 进行设置,并且仅正确填充大写字母。ansible-playbookwhen

检查运行良好:

- name: Check CDB
  connection: local
  oracle_sql:
    hostname: "{{ db_hostname }}"
    service_name: "{{ rcs_db_service }}"
    user: "{{ db_connect_user }}"
    password: "{{ db_connect_password }}"
    mode: "{{ db_connect_mode }}"
    sql: "SELECT value FROM v$parameter WHERE name = 'enable_pluggable_database'"
  register: cdb_on

结果是:

ok: [hostname] => {
    "changed": false,
    "invocation": {
        "module_args": {
            "hostname": "hostname",
            "mode": "sysdba",
            "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
            "port": "xxxx",
            "script": null,
            "service_name": "dbname",
            "sql": "SELECT value FROM v$parameter WHERE name = 'enable_pluggable_database'",
            "user": "SYS"
        }
    },
    "msg": [
        [
            "FALSE"
        ]
    ]
}

Oracle SQL 任务的(预期)返回值为”FALSE"

我尝试了不同的条件运行,例如。似乎 Ansible 可以采用 as 布尔值,但它不适用于FALSE

- name: run
  when: cdb_on | bool == FALSE

如果我尝试将其用作文字,也是如此

- name: run
  when: cdb_on == '"FALSE"'

- name: run
  when: cdb_on | upper == "FALSE"

- name: run
  when: cdb_on == 'FALSE'

结果始终是相同的 - 应该运行的下一个任务/语句总是被跳过。playbook 始终以红色突出显示为布尔值。FALSE

我怎样才能让条件作为文字工作?

如上所示的不同掩码,需要条件 with 才能使其运行。FALSE

Ansible 布尔值

评论


答:

0赞 U880D 11/15/2023 #1

问:“我怎样才能让条件起作用?

似乎 Ansible 将 FALSE 视为布尔值

是的,它可以。因此,它更简单,只需布尔过滤器 - 转换为布尔值。唯一需要做的工作是 oracle_sql 模块的返回值的数据结构,因为它提供了一个带有列表列表的消息

最小的示例 playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    cdb_on:
      msg: [
        [
           "FALSE"
        ]
      ]

  tasks:

  - debug:
      msg: "cdb_on.msg: {{ cdb_on.msg }} is of type {{ cdb_on.msg | type_debug }}"

  - debug:
      msg: "CDB is not ON!"
    when: not (cdb_on.msg | flatten | first ) | bool

将导致

TASK [debug] **************************************
ok: [localhost] =>
  msg: 'cdb_on.msg: [[u''FALSE'']] is of type list'

TASK [debug] **************************************
  msg: CDB is not ON!

背景信息

根据 ansible/plugins/filter/core.py - to_bool 将把所有不在False

    if isinstance(a, string_types):
        a = a.lower()
    if a in ('yes', 'on', '1', 'true', 1):
        return True
    return False

所以即使是这样的事情

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

     VAR: "TEST"

  tasks:

  - debug:
      msg: "VAR: {{ VAR }} is of type {{ VAR | type_debug }}"

  - debug:
      msg: "Value is not True!"
    when: not VAR | bool

将导致

TASK [debug] *******************************
ok: [localhost] =>
  msg: 'VAR: TEST is of type AnsibleUnicode'

TASK [debug] *******************************
ok: [localhost] =>
  msg: Value is not True!

另请参阅 Boolean 变量