我有这个Ansible任务文件,它基于变量harbor_patch__vm_region执行5个选项之一。我希望实现完全相同的行为,将代码重构为(可能)一行或尽可能少的行。
只为条件变量重复5次相同的行对我来说是不正确的。有更好的方法吗?
# file: harbor-patch/tasks/modify-scripts.yml
---
- name: "{{ __tpfx }}modify-scripts | Modify the scripts to use the Boadilla satellite"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
line: SAT=AAA.111.222.333.com
when: harbor_patch__vm_region == "bo" or harbor_patch__vm_region == "az"
# CAN
- name: "{{ __tpfx }}modify-scripts | Modify the scripts to use the Cantabria satellite"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
line: SAT=BBB.111.222.333.com
when: harbor_patch__vm_region == "cn"
# MX
- name: "{{ __tpfx }}modify-scripts | Modify the scripts to use the Mexico satellite"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
line: SAT=CCC.111.222.333.com
when: harbor_patch__vm_region == "mx"
# CHI
- name: "{{ __tpfx }}modify-scripts | Modify the scripts to use the Chile satellite"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
line: SAT=DDD.111.222.333.com
when: harbor_patch__vm_region == "cl"
# UK
- name: "{{ __tpfx }}modify-scripts | Modify the scripts to use the UK satellite"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
line: SAT=EEE.111.222.333.com
when: harbor_patch__vm_region == "uk"发布于 2022-11-22 17:37:44
在vars中的某个地方为数据创建一个dict:
my_sats:
az: AAA.111.222.333.com
bo: AAA.111.222.333.com
cn: BBB.111.222.333.com
mx: CCC.111.222.333.com
cl: DDD.111.222.333.com
uk: EEE.111.222.333.com然后添加具有正确值的行:
- name: "{{ __tpfx }}modify-scripts | Modify the scripts to use the correct satellite"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
line: "SAT={{ my_sats[harbor_patch__vm_region] | d('') }}"
when: my_sats[harbor_patch__vm_region] is defined默认值只是为了避免在遇到未定义区域时出现可能的ansible错误,并且将永远不会插入,因为when子句会对此进行精确检查。
请注意,如果在两次运行之间更改区域,上面的代码将不会替换脚本中的行。如果这是您想要实现的,您需要修改您的任务:
- name: "{{ __tpfx }}modify-scripts | Modify the scripts to use the correct satellite"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
regexp: "^SAT=.*$"
line: "SAT={{ my_sats[harbor_patch__vm_region] | d('') }}"
when: my_sats[harbor_patch__vm_region] is defined不过,如果您碰到一个未定义的区域,这不会改变任何事情。如果要删除行以防止区域未知,则需要添加第二个任务。
- name: "{{ __tpfx }}modify-scripts | Remove SAT for unknown regions"
lineinfile:
path: '{{ harbor_patch__dest_directory }}/set_patch_env.sh'
regexp: "^SAT=.*$"
state: absent
when: my_sats[harbor_patch__vm_region] is not definedhttps://stackoverflow.com/questions/74536229
复制相似问题