set_fact 的语法

set_fact 的语法

我的 Ansible 库存文件如下:

[dev_web:children]
dev_www
dev_auto

[dev_www]
web01_dev    ansible_host=web01-dev.company.com
web02_dev    ansible_host=web02-dev.company.com
web03_dev    ansible_host=web03-dev.company.com

[dev_auto]
auto_dev     ansible_host=auto-dev.company.com

Ansible 剧本“/deploys/patch.yml”为:

- name: patch
  hosts: "{{ configs_target | default('test_servers') }}"
  serial: 1
  vars:
    slack_token: 'slack-token'
    slack_channel: 'slack-channel'
  roles:
    - patch

主 Ansible playbook 文件“/deploys/roles/patch/tasks/main.yml”为:

---
- name: Include vars of patch.yml
  include_vars:
    file: backend_vars.yml
    name: web_servers

- name: set needed facts
  set_fact:
    backend_name: "{{ [cache_mgmt][configs_target]['backend_name'] }}"

变量文件“/deploys/roles/patch/vars/backend_vars.yml”为:

cache_mgmt:
  dev_web:
    backend_name: www_http_be
    backend_hosts: dev_www
  dit_web:
    backend_name: www_http_be
    backend_hosts: dit_www

我执行的运行命令是:

ansible-playbook /deploys/patch.yml -e '{“configs_target”:“dev_web”}'

当我运行剧本时,我期望变量的值为backend_name: www_http_be。但是,它失败并出现以下错误。

TASK [patch : set needed facts] *****************************************************************************************
fatal: [web01_dev]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'dev_web'\n\nThe error appears to be in '/deploys/roles/patch/tasks/main.yml': line , column , but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: set needed facts\n  ^ here\n"}

我认为问题出在 set_fact 的语法上。如果是真的,那么在这种情况下正确的形式应该是什么?

答案1

由于变量是从变量文件调用的,因此我们还必须提及分配的名称。正确的语法是"{{ web_servers['cache_mgmt'][configs_target]['backend_name'] }}"

相关内容