ansible进阶小技巧--tags

      用ansible写playbook的朋友可能会发现,当配置工作很多时,如果在中间过程出错了,修改后想重新执行,前面的一大堆步骤让人感觉很烦躁。虽然提供了“retry”文件,但是却只是根据host来判断重新执行,仍然不够方便;又或者,中间的某些步骤特别耗时,比如下载一个很大的数据包,每次执行特别浪费时间,想要特别的跳过。怎么办?我猜你就是把不需要的部分给注释掉了。有没有更好的办法呢?

        当然,现在流行的ansible有提供一种方法解决这个问题。

        ansible的playbool中有一个关键字,叫做tags。tags是什么?就是打标签。tags可以和一个play(就是很多个task)或者一个task进行捆绑。然后,ansible-playbook提供了“--skip-tags”和“--tags” 来指明是跳过特定的tags还是执行特定的tags。

        下面请看例子。

[plain] view plaincopy
  1. <pre class="plain" name="code"># example 1 test1.yml  
  2. - hosts: test-agent  
  3.   tasks:  
  4.     - command: echo test1  
  5.       tags:                       可以写在一行  tags: test1
  6.          - test1  
  7.     - command: echo test2  
  8.       tags:   
  9.          - test2  
  10.     - command: echo test3  
  11.       tags:   
  12.          - test3  

       当执行  ansible-playbook test1.yml --tags="test1,test3"  ,则只会执行 test1和test3的echo命令。

       当执行  ansible-playbook test1.yml --skip-tags="test2"  ,同样只会执行 test1和test3的echo命令。

    同理可以适用于play,请看例子

[plain] view plaincopy
  1. # example 2 test2.yml  
  2. - hosts: test-agent1  
  3.   tags:   
  4.      - play1  
  5.   tasks:  
  6.      - command: echo This is  
  7.      - command: echo agent1  
  8. - hosts: test-agent2  
  9.   tags:   
  10.      - play2  
  11.   tasks:  
  12.      - command: echo This is  
  13.      - command: echo agent2  
  14. - hosts: test-agent3  
  15.   tags:   
  16.      - play3  
  17.   tasks:  
  18.      - command: echo This is  
  19.      - 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

[plain] view plaincopy
  1. - include: foo.yml tags=web,foo  
[plain] view plaincopy
  1. roles:  
  2.   - { 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呢?答案是肯定的。而且,没有开玩笑。不行你试试。下面举例

       

[plain] view plaincopy
  1. <pre class="plain" name="code"># example 3 test3.yml  
  2. - command: echo task111  
  3.   tags:  
  4.      - task1  
  5. - command: echo task112  
  6.   tags:  
  7.      - task1  
  8. - command: echo task333  
  9.   tags:  
  10.      - task3  
  11. - command: echo task222  
  12.   tags:  
  13.      - 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的部分,没有影响,正常顺序执行。

原文地址:https://www.cnblogs.com/wjoyxt/p/5029658.html