2017-05-24 17 views
0

我嘗試創建一個條件邏輯,以基於從命令行傳入的環境變量「branch」針對不同的節點組運行。在主持人劇本中創建if ... else語句的正確方法/語法

下面是我的代碼示例。 分支是我傳入的變量。如果branch =='test',我將選擇組的'upgrade-CI-test'作爲targeted_host作爲我的下一個任務,除test之外的任何內容都將保留變量的值「upgrade_version」

但是,由於某些原因,我無法在測試組上執行「從升級機器中刪除舊腳本」。我不確定這是否是正確的設置變量?我是新手,任何提示將不勝感激。

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

回答

0

如果你有劇本分析時定義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 
+0

是否可以在上層定義變量,類似於我在示例中所做的操作?原因在於如果我有多個遊戲,那麼我已經更改了所有主機部分的主機部分? –

+0

更新我的回答 –

+0

我將組['升級CI測試']升級到'升級CI測試'後,它對我來說工作正常。非常感謝你 –