用ansible寫playbook的朋友可能會發現,當配置工作很多時,如果在中間過程出錯了,修改后想重新執行,前面的一大堆步驟讓人感覺很煩躁。雖然提供了“retry”文件,但是卻只是根據host來判斷重新執行,仍然不夠方便;又或者,中間的某些步驟特別耗時,比如下載一個很大的數據包,每次執行特別浪費時間,想要特別的跳過。怎么辦?我猜你就是把不需要的部分給注釋掉了。有沒有更好的辦法呢?
當然,現在流行的ansible有提供一種方法解決這個問題。
ansible的playbool中有一個關鍵字,叫做tags。tags是什么?就是打標簽。tags可以和一個play(就是很多個task)或者一個task進行捆綁。然后,ansible-playbook提供了“--skip-tags”和“--tags” 來指明是跳過特定的tags還是執行特定的tags。
下面請看例子。
- <pre class="plain" name="code"># example 1 test1.yml
- - hosts: test-agent
- tasks:
- - command: echo test1
- tags: 可以寫在一行 tags: test1
- - test1
- - command: echo test2
- tags:
- - test2
- - command: echo test3
- tags:
- - test3
當執行 ansible-playbook test1.yml --tags="test1,test3" ,則只會執行 test1和test3的echo命令。
當執行 ansible-playbook test1.yml --skip-tags="test2" ,同樣只會執行 test1和test3的echo命令。
同理可以適用於play,請看例子
- # example 2 test2.yml
- - hosts: test-agent1
- tags:
- - play1
- tasks:
- - command: echo This is
- - command: echo agent1
- - hosts: test-agent2
- tags:
- - play2
- tasks:
- - command: echo This is
- - command: echo agent2
- - hosts: test-agent3
- tags:
- - play3
- tasks:
- - command: echo This is
- - command: echo agent3
當執行 ansible-playbook test2.yml --tags="play1,play3" ,則只會執行 play1和play3的tasks。
當執行 ansible-playbook test2.yml --skip-tags="play2" ,同樣只會執行 test1和test3的tasks。
同理還有include和role
- - include: foo.yml tags=web,foo
- roles:
- - { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }
你肯定注意到了,這個的一個include和role,同時打了多個tags。是的,這是允許的,而且不同的tags名稱是等效的。多個tags對play和task同樣適用。--skip-tags="web"和--skip-tags="foo",效果是一樣的。如果是--skip-tag="web,foo"呢?效果還是一樣的。呵呵開玩笑的,我沒有試過,歡迎你試一下。
既然一個job可以有多個tags,那么多個job是否可以有同一個tags呢?答案是肯定的。而且,沒有開玩笑。不行你試試。下面舉例
- <pre class="plain" name="code"># example 3 test3.yml
- - command: echo task111
- tags:
- - task1
- - command: echo task112
- tags:
- - task1
- - command: echo task333
- tags:
- - task3
- - command: echo task222
- tags:
- - task2
當執行 ansible-playbook test2.yml --skip-tags="play1" ,則只會執行 task3和task2的tasks,task1中的2個task都被skip了。
當執行 ansible-playbook test2.yml --tags="task2,task3" ,仍然只會執行 task3和task2的tasks,並且請注意,是按照playbooks中代碼的順序執行,而不是--tags中參數的順序執行。
ansible是根據輸入的tags的參數,與playbook中進行比較,按照playbook的執行順序,跳過或執行特定的tags。對於沒有打tags的部分,沒有影響,正常順序執行。
