Ansible:仅当标记有特定标签时才运行播放

Ansible:仅当标记有特定标签时才运行播放

我尝试使用 Ansibleansible 2.4.2.0从主剧本中只运行某个剧本 ( main.yml)

---
# main playbook for cluster deployment

  # initial configuration of OS same for all hosts
- name: Cluster Deployer playbook
  hosts: all
  roles:
    - { role: common, tags: ['initial_config'] }


  # configuration specific for loadbalancers hosts group
- name: Cluster Deployer playbook - Load Balancer setup
  hosts: loadbalancers
  roles:
    - { role: loadbalancers_setup, tags: ['setup_loadbalancer'] }

  # configuration specific for db-servers hosts group
- name: Cluster Deployer playbook - Database servers setup
  hosts: db-servers
  roles:
   - { role: db_servers_setup, tags: ['setup_db_server'] }

  # configuration specific for web-servers hosts group
- name: Cluster Deployer playbook - Web Servers setup
  hosts: web-servers
  roles:
   - { role: web_servers_setup, tags: ['setup_web_server'] }

这是我的hosts文件

[loadbalancers]
192.168.99.10

[db-servers]
192.168.99.2

[web-servers]
192.168.99.3
192.168.99.4

我正在使用以下命令调用剧本

ansible-playbook main.yml --inventory hosts --tags initial_config

问题是,即使我只请求了部分initial_config中带有标签的剧本,Ansible 也会运行该剧本中的所有剧本roles。我尝试设置tags下面的部分hosts,但没有成功。

是否可以在此级别定义标签,而无需在角色中标记单个任务?我是 Ansible 的新手,因此如果有更好的编写剧本的方法,我很乐意听取。

答案1

您的代码中的“tag”指令放错了位置。

您的代码看起来应如下所示:

---
# main playbook for cluster deployment

  # initial configuration of OS same for all hosts
- name: Cluster Deployer playbook
  hosts: all
  roles:
    - common
  tags: 
    - initial_config

  # configuration specific for loadbalancers hosts group
- name: Cluster Deployer playbook - Load Balancer setup
  hosts: loadbalancers
  roles:
    - loadbalancers_setup
  tags: 
    - setup_loadbalancer

  # configuration specific for db-servers hosts group
- name: Cluster Deployer playbook - Database servers setup
  hosts: db-servers
  roles:
    - db_servers_setup
  tags: 
    - setup_db_server

  # configuration specific for web-servers hosts group
- name: Cluster Deployer playbook - Web Servers setup
  hosts: web-servers
  roles:
    - web_servers_setup
  tags:
    - setup_web_server

你的 ansible 命令看起来应该像这样:

ansible-playbook main.yml --inventory hosts --tags "initial_config"

如需了解更多信息,请查看Ansible 的官方文档。

答案2

看起来您对这里的标签继承有误解:

标签继承

您可以将标签应用于多个任务,但它们仅影响任务本身。在其他任何地方应用标签只是为了方便,这样您不必在每个任务上都写它。关于标签继承的 Ansible 文档

尝试这样的操作:

- name: Cluster Deployer playbook
  hosts: all
  tasks:
    - include_role:
        name: common
      tags:
       - inital_config

相关内容