2

如何使用tower_grouptower_host模块将主机添加到组?

以下代码创建了一个主机和一个组,但它们彼此无关:

---
- hosts: localhost
  connection: local
  gather_facts: false

  tasks:
    - tower_inventory:
        name: My Inventory
        organization: Default
        state: present
        tower_config_file: "~/tower_cli.cfg"

    - tower_host:
        name: myhost
        inventory: My Inventory
        state: present
        tower_config_file: "~/tower_cli.cfg"

    - tower_group:
        name: mygroup
        inventory: My Inventory
        state: present
        tower_config_file: "~/tower_cli.cfg"

文档提到instance_filters参数(“匹配主机的过滤表达式的逗号分隔列表。”),但没有提供任何使用示例。

添加instance_filters: myhosttower_group任务没有效果。

4

2 回答 2

1

这在 Tower 附带的模块中并不原生提供,这些模块较旧并使用已弃用的tower-cli包。

但它在使用CLI 的较新的AWX 集合awx中可用,只要您有足够新的 Ansible(2.9 应该没问题)。

本质上就是通过一个需求文件安装awx集合,或者直接like

ansible-galaxy collection install awx.awx -p ./collections

awx.awx集合添加到您的剧本

collections:
  - awx.awx

然后使用hosts:选项tower_group:.

- tower_group:
    name: mygroup
    inventory: My Inventory
    hosts:
      - myhost
    state: present

您可以在此处查看演示手册

请注意,如果您的组已经包含其他主机,您可能需要preserve_existing_hosts: True 。不幸的是,似乎没有一种简单的方法可以从组中删除单个主机。

就您的示例而言,这可能会起作用:

---
- hosts: localhost
  connection: local
  gather_facts: false
  collections:
    - awx.awx

  tasks:
    - tower_inventory:
        name: My Inventory
        organization: Default
        state: present
        tower_config_file: "~/tower_cli.cfg"

    - tower_host:
        name: myhost
        inventory: My Inventory
        state: present
        tower_config_file: "~/tower_cli.cfg"

    - tower_group:
        name: mygroup
        inventory: My Inventory
        state: present
        tower_config_file: "~/tower_cli.cfg"
        hosts:
          - myhost
于 2021-07-02T20:31:44.713 回答
1

我使用 Ansible shell 模块和 tower-cli 解决了这个问题。我知道创建一个 ansible 模块比它更好,但是对于一个快速的解决方案......

- hosts: awx
  vars:
  tasks: 
   - name: Create Inventory
     tower_inventory:
       name: "Foo Inventory"
       description: "Our Foo Cloud Servers"
       organization: "Default"
       state: present
   - name: Create Group
     tower_group: 
       inventory: "Foo Inventory" 
       name:  Testes 
     register: fs_group 
   - name: Create Host
     tower_host:
       inventory: "Foo Inventory" 
       name: "host"  
     register: fs_host 
   - name: Associate host group 
     shell: tower-cli host associate  --host "{{fs_host.id}}" --group "> {{fs_group.id}}"
于 2018-08-29T03:56:45.717 回答