我试图根据Ansible将部署这些文件的机器上存在的主板版本来选择一个本地文件。
因此,我的方法是使用字典格式{"“:".yml"}。并使用此字典填充一个新变量(此处为pcu_config),该变量将最终存储ansible使用的文件的名称。到目前为止,我已经在实现中看到了,并且在行中得到了未定义的变量错误
vars_files:
- "{{ playbook_dir }}/pcu_config/{{ pcu_config }}"但是,正如在此播放之前的输出图像中的调试 msg中所看到的,pcu_config确实是定义的(并且也是正确的文件名)。
- name: Find the pcu_config
hosts: vehicle
gather_facts : no
vars:
pcu_config_dict:
VirtualBox: virtual.yml
n1: n1.yml
n2: n2.yml
n3: n3.yml
n4a: n4a.yml
n4b: n4b.yml
tasks:
- name: Find the motherboard name
shell: cat /sys/devices/virtual/dmi/id/board_name
register: board_name
- name: Find the motherboard version
shell: cat /sys/devices/virtual/dmi/id/chassis_version
register: board_version
- debug:
msg: "board_name : {{ board_name.stdout }}, board_version: {{ board_version.stdout }}, {{pcu_config_dict}} "
- name: Assign the PCU_config file for other than n4's
set_fact:
pcu_config: '{{pcu_config_dict[ board_name.stdout | default("this cpu does not exist in the dict")] | default("") }}'
when: board_name.stdout != "n4"
- name: Assign the PCU_config file for n4
set_fact:
pcu_config: '{{pcu_config_dict[board_version.stdout | default("this cpu_version does not exist in the dict")] | default("") }}'
when: board_name.stdout == "n4"
- name : Check pcu_config is available elsewhere in playbook
hosts: vehicle
tasks:
- debug:
msg: "{{ pcu_config }}, {{ playbook_dir }}"
- name: Deploy software to vehicle
hosts: vehicle
vars_files:
- "{{ playbook_dir }}/pcu_config/{{ pcu_config }}"
- "{{ playbook_dir }}/os_config/deb-files-cache.yml"
- "{{ playbook_dir }}/os_config/python_dep.yml"
roles:
- role: logger_network
tags: base这是我在虚拟机上运行这个剧本时的输出。

欢迎提出解决X或Y问题的建议。(参考@Zeitounator的评论)
发布于 2022-01-29 14:20:11
这不是最好的方法,而是访问set_facts在剧本中其他地方设置的变量,使用cacheable: yes工作。
- name: Assign the PCU_config file for other than n4's
set_fact:
pcu_config: '{{pcu_config_dict[ board_name.stdout | default("this cpu does not exist in the dict")] | default("") }}'
cacheable: yes
when: board_name.stdout != "n4"
- name: Assign the PCU_config file for n4
set_fact:
pcu_config: '{{pcu_config_dict[board_version.stdout | default("this cpu_version does not exist in the dict")] | default("") }}'
cacheable: yes
when: board_name.stdout == "n4"https://stackoverflow.com/questions/70876116
复制相似问题