ansible进阶小技巧(1)--tags,ansible--tags


        用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: 
         - 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的部分,没有影响,正常顺序执行。

好了,ansible的tags鄙人就了解这么多,欢迎大家使用tasks管理ansible的playbook。





相关内容

    暂无相关文章