Python 在ansible playbook for hosts中创建if…else语句的正确方法/语法
我尝试根据从命令行传入的环境变量“branch”创建一个条件逻辑,以针对不同的节点组运行 下面是我的代码示例branch是我传入的变量。如果branch=='test',我将选择组'upgrade CI test'作为下一个任务的目标主机,test以外的任何内容都将保留变量“upgrade\u version”的值 但是,由于某些原因,我无法在测试组上执行我的“从升级机器删除旧脚本”游戏。我不确定设置变量是否正确?我是ansible的新手,如有任何提示,将不胜感激Python 在ansible playbook for hosts中创建if…else语句的正确方法/语法,python,ansible,Python,Ansible,我尝试根据从命令行传入的环境变量“branch”创建一个条件逻辑,以针对不同的节点组运行 下面是我的代码示例branch是我传入的变量。如果branch=='test',我将选择组'upgrade CI test'作为下一个任务的目标主机,test以外的任何内容都将保留变量“upgrade\u version”的值 但是,由于某些原因,我无法在测试组上执行我的“从升级机器删除旧脚本”游戏。我不确定设置变量是否正确?我是ansible的新手,如有任何提示,将不胜感激 --- - name: Set
---
- name: Set targeted hosts based on git branch
hosts: localhost
tasks:
- name: Set hosts variable
vars:
targeted_host: "{{groups['upgrade-CI-test'] if branch == 'test' else upgrade_version }}"
debug:
var: targeted_host
- name: Remove old scripts from upgrade machine
hosts: targeted_host
tasks:
- name: Remove any old wrapper scripts
win_file:
path: D:\my_path
state: absent
如果在playbook解析时定义了
分支
和升级版本
变量,则可以执行以下操作:
---
- name: Remove old scripts from upgrade machine
hosts: "{{ 'upgrade-CI-test' if branch == 'test' else upgrade_version }}"
tasks:
- name: Remove any old wrapper scripts
win_file:
path: D:\my_path
state: absent
更新:如果您有多个重头戏,您可以使用group_by
创建动态组并将其用于您的重头戏
---
- name: Make dynamic group
hosts: "{{ 'upgrade-CI-test' if branch == 'test' else upgrade_version }}"
tasks:
- group_by:
key: my_new_group
- name: Remove old scripts from upgrade machine
hosts: my_new_group
tasks:
- name: Remove any old wrapper scripts
win_file:
path: D:\my_path
state: absent
- name: Do some other stuff
hosts: my_new_group
tasks:
- debug:
msg: hello
是否可以在上层定义一个变量,类似于我在示例中所做的?原因是,如果我有多个重头戏,那么我必须更改所有重头戏的主机部分?更新我的回答在我将组['upgrade-CI-test']改为'upgrade-CI-test']后,对我来说效果很好。多谢各位