Ansible 处理程序 include_task 不适用于标签

问题描述 投票:0回答:1

我在尝试使用处理程序中的标签调用包含任务时遇到问题。执行时,它会忽略标签并执行剧本的所有任务

服务.yaml

- name: stop service
  become: true
  systemd:
    name: httpd
    state: stopped
  tags: stop

- name: start service
  become: true
  systemd:
    name: httpd
    state: started
  tags: start

main.yaml

- hosts: webservers
  tasks:
    - name: ask stop / start
      pause:
        prompt: "please type start or stop"
        echo: yes
      register: ask
      changed_when: true
      notify: service
      tags: restarting
   
  handlers:
    - name: service
      include_tasks: services.yaml
      tags: "{{ ask.user_input }}"

执行

ansible-playbook main.yam -t restarting

当我运行它时,它会启动所有忽略标签的任务。

ansible ansible-2.x
1个回答
2
投票

在处理程序上使用 tags 是没有意义的。处理程序要么被通知,要么不被通知。如果您想有条件地运行处理程序,请使用条件,例如

shell> cat services.yaml
- debug:
    msg: stop service
  when: ask.user_input == 'stop'

- debug:
    msg: start service
  when: ask.user_input == 'start'

然后是剧本

shell> cat pb.yml
- hosts: localhost
  tasks:
    - name: ask stop / start
      pause:
        prompt: "please type start or stop"
        echo: true
      register: ask
      changed_when: true
      notify: service
      tags: [restarting, never]
  handlers:
    - name: service
      include_tasks: services.yaml

给予

shell> ansible-playbook pb.yml -t restarting

PLAY [localhost] ***********************************************************

TASK [ask stop / start] ****************************************************
[ask stop / start]
please type start or stop:
changed: [localhost]

RUNNING HANDLER [service] **************************************************
included: /export/examples/example-269/services.yaml for localhost

RUNNING HANDLER [debug] ****************************************************
skipping: [localhost]

RUNNING HANDLER [debug] ****************************************************
ok: [localhost] => 
  msg: start service

PLAY RECAP *****************************************************************
localhost: ok=3 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

添加 never 标签,仅在选择 restarting 时才要求输入。

© www.soinside.com 2019 - 2024. All rights reserved.