正确的方法/语法在主机

时间:2017-05-24 19:25:45

标签: python ansible

我尝试根据从命令行传入的环境变量“branch”创建一个条件逻辑来针对不同的节点组运行。

以下是我的代码示例。 分支 是我传入的变量。如果branch =='test',我会选择“upgrade-CI-test”组作为我的下一个任务的targeted_host,任何事情除测试外,将保留变量“upgrade_version”的值

但是,由于某些原因,我无法在测试组中执行“从升级计算机中删除旧脚本”。我不确定这是否是正确的设置变量?我是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

1 个答案:

答案 0 :(得分:0)

如果您在playbook解析时定义了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

更新:如果您有多个游戏,则可以使用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