ansible set_fact 无法访问

ansible set_fact not accessible

我有这个 ansible 剧本

- name: set var small
  set_fact:
    iops_price = 41538
    ram_price_id = 32438
    second_san_price_id = 32926
    os_price_id = 49061
  when: plan|lower == 'small'

- name: aa
  command: echo "{{iops_price}}"

它失败了,因为它说 iops_price 未定义,这是输出:

TASK [set var small] ***********************************************************
task path: /home/hanna/proj/db2onc-deploy/db.yml:98
ok: [localhost] => {"ansible_facts": {"_raw_params": "iops_price = 41538  ram_price_id = 32438 second_san_price_id = 32926 os_price_id = 49061"}, "changed": false}

TASK [aa] **********************************************************************
task path: /home/hanna/proj/db2onc-deploy/db.yml:107
fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'iops_price' is undefined\n\nThe error appears to have been in '/home/hanna/proj/db2onc-deploy/db.yml': line 107, column 9, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n      - name: aa\n        ^ here\n"}

事实证明,我设置的事实可以通过 _raw_params 访问,相当于

_raw_params = "iops_price = 41538 ram_price_id = 32438 second_san
_price_id = 32926 os_price_id = 49061"

这不是我想要的,我实际上想设置那些单独的变量,有人知道为什么会这样吗?

您可以在 set_fact.

中使用冒号 (:) 而不是等号 (=)

这应该有效:

- name: set var small
  set_fact:
    iops_price: 41538
    ram_price_id: 32438
    second_san_price_id: 32926
    os_price_id: 49061
  when: plan|lower == 'small'

- name: aa
  command: echo "{{iops_price}}"

我经常发现,在 YAML 中,如果周围有 space,它不会将“=”解析为字段。尝试:

  set_fact:
    iops_price=41538
    ram_price_id=32438
    second_san_price_id=32926
    os_price_id=49061
  when: plan|lower == 'small'