简体   繁体   English

正确的方式/语法,如果在主机的ansible剧本中创建if ... else语句

[英]Correct way/syntax to create if …else statement in ansible playbook for hosts

I try to create a conditional logic to run against different group of nodes based on the environment variable "branch" I pass in from the command line. 我尝试根据从命令行传递的环境变量“分支”创建条件逻辑,以针对不同的节点组运行。

Below is my code sample. 下面是我的代码示例。 branch is the variable I pass in. If branch == 'test', I will pick the group 'upgrade-CI-test' as targeted_host for my next task, anything other than test will retain the value of the variable "upgrade_version" branch是我传入的变量。如果branch =='test',我将选择组'upgrade-CI-test'作为我的下一个任务的targeted_host,test以外的任何内容都将保留变量“ upgrade_version”的值。

However, I can't get my play "Remove old scripts from upgrade machine" executed on the test group for some reasons. 但是,由于某些原因,我无法在测试组上执行我的剧本“从升级机中删除旧脚本”。 I'm not sure if that's the correct the set up variable? 我不确定设置变量是否正确? I'm new to ansible, any hints will be appreciated. 我是ansible的新手,任何提示将不胜感激。

---
- 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

If you have branch and upgrade_version variables defined at playbook parse time, then you can do: 如果您在剧本解析时定义了branchupgrade_version变量,则可以执行以下操作:

---
- 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

Update: if you have multiple plays, you can use group_by to make dynamic group and use it for your plays. 更新:如果您有多个剧本,则可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM