How can I apply a tag to every command in an Ansible tasks file?

时间:2016-04-04 18:48:56

标签: ansible

The Ansible best-practices documentation has this example code:

---
# file: roles/common/tasks/main.yml

- name: be sure ntp is installed
  yum: name=ntp state=installed
  tags: ntp

- name: be sure ntp is configured
  template: src=ntp.conf.j2 dest=/etc/ntp.conf
  notify:
    - restart ntpd
  tags: ntp

- name: be sure ntpd is running and enabled
  service: name=ntpd state=running enabled=yes
  tags: ntp

I'm looking to avoid duplicating the tags: ntp line. Is it possible for each of these instructions to inherit a tag?

2 个答案:

答案 0 :(得分:10)

你可以使用 - 阻止:

➜  ~ cat become.yml
---
- hosts: localhost
  user: vagrant
  tasks:
   - block:
      - shell: whoami
        register: result

      - debug: var=result.stdout

      - name: become_root_user
        become: true
        become_user: root
        shell: whoami
        register: sudo_test_result

      - debug: var=sudo_test_result.stdout
     tags:
      - block1
   - block:
      - name: creating_new_app_user
        become: true
        become_user: root
        become_method: sudo
        user: name=app_user password=Bzs310di86b6E groups="adm,sudo" system=yes state=present

      - name: become_app_user
        become: true
        become_user: app_user
        become_method: sudo
        shell: whoami
        register: app_user_test_result

      - debug: var=app_user_test_result.stdout
     tags:
      - block2

~ansible-playbook -i realtime-automation / hosts-slaves become.yml --tags" block1"

在您的具体案例中:

---
- block:
    - name: be sure ntp is installed
      yum: name=ntp state=installed

    - name: be sure ntp is configured
      template: src=ntp.conf.j2 dest=/etc/ntp.conf
      notify:
        - restart ntpd

    - name: be sure ntpd is running and enabled
      service: name=ntpd state=running enabled=yes
  tags: ntp

答案 1 :(得分:7)

在v2之前,可以实现为'include'

分配标签

将此任务移至另一个文件,例如ntp.yml

---
# file: roles/common/tasks/ntp.yml

- name: be sure ntp is installed
  yum: name=ntp state=installed

- name: be sure ntp is configured
  template: src=ntp.conf.j2 dest=/etc/ntp.conf
  notify:
    - restart ntpd

- name: be sure ntpd is running and enabled
  service: name=ntpd state=running enabled=yes

然后将其包含在main.yml

---
# file: roles/common/tasks/main.yml
- include: ntp.yml
  tags: ntp