如何在Ansible中为变量添加条件化后缀?
问题与优化方案
当前实现现状
目前我通过include_vars模块加载不同操作系统对应的补丁bundle变量,代码运行正常,但每个月都要修改所有被引用的bundle.yml文件,维护起来很麻烦。
当前代码:
- name: Setting OS specific bundle variable include_vars: "{{ item }}" with_first_found: - files: - "vars/{{ ansible_distribution }}_{{ ansible_distribution_major_version }}/bundle.yml" - "vars/default.yml"
核心需求
想改成在主剧本里只定义一个基础的bundle变量,然后根据操作系统条件动态修改它的值——针对RedHat 6系统,自动给bundle字符串加上ELS后缀。比如基础值是1Q2023,RH6系统下要变成1Q2023ELS。
优化后的实现
直接在主剧本里定义基础变量,再通过set_fact任务动态调整:
vars: bundle: 1Q2023 tasks: - name: 为RH6系统设置带ELS后缀的bundle值 set_fact: bundle: "{{ bundle }}ELS" when: ansible_distribution == "RedHat" and ansible_distribution_major_version == "6"
注意:这里要把ansible_distribution_major_version和字符串"6"做比较,避免类型匹配问题;字符串拼接用{{ bundle }}ELS的写法更符合Ansible的语法规范。
内容的提问来源于stack exchange,提问作者andrew
相关产品推荐
相关产品推荐

