Ansible技术问询:从文件加载变量,文件不存在时设为空并解决变量不可变问题
问题:从文件加载变量,不存在时设为空字典(含重复执行变量不可变问题)
需求与背景
- 核心需求:从指定文件加载变量,若文件不存在则将目标变量设为空字典
- 遇到的问题:该逻辑放在
included_task中会多次运行,使用set_fact设置变量后,变量会变为不可变,导致后续执行时无法更新变量值
最初实现代码
- name: load configuration file ansible.builtin.include_vars: file: config_filename name: configuration_content when: lookup('file', config_filename, errors='warn') - name: set component_config when file is not found set_fact: configuration_content: {} when: not lookup('file', component_config_file, errors='warn')
问题表现
第一次运行时逻辑正常,但第二次运行时,即使config_filename存在,configuration_content仍会保持为空字典,无法被文件中的内容更新。
临时解决方案(较为繁琐)
- name: load configuration file ansible.builtin.include_vars: file: config_filename name: configuration_file_content when: lookup('file', config_filename, errors='warn') - name: set component_config when file is found set_fact: configuration_content: "{{ configuration_file_content }}" when: lookup('file', component_config_file, errors='warn') - name: set component_config when file is not found set_fact: configuration_content: {} when: not lookup('file', component_config_file, errors='warn')
简洁解决方案
利用lookup的默认值特性,结合from_yaml过滤器,用单任务完成需求,同时避免变量不可变问题:
- name: load configuration or set empty dict set_fact: configuration_content: "{{ lookup('file', config_filename, errors='warn') | default('{}', true) | from_yaml }}"
逻辑说明
lookup('file', config_filename, errors='warn'):尝试读取目标文件,文件不存在时返回空字符串并输出警告default('{}', true):强制在lookup返回空值(或执行失败)时,使用默认的空字典字符串from_yaml:将字符串解析为YAML格式,最终得到文件中的配置内容或空字典
这种方式无需拆分多个任务,一次赋值即可完成需求,同时避免了多次set_fact导致的变量不可变问题。
内容的提问来源于stack exchange,提问作者Chris Maes
相关产品推荐
相关产品推荐

