如何在Ansible Tower库存中将主机添加到组中?

时间:2018-07-23 06:15:59

标签: ansible ansible-tower

如何使用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: myhost任务中添加tower_group无效。

2 个答案:

答案 0 :(得分:1)

这在 Tower 附带的模块中本身不可用,这些模块较旧且使用已弃用的 tower-cli 包。

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

本质上,install the awx collection通过一个需求文件,或者直接像

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

您可以看到 demo playbook here

请注意,如果您的组已经包含其他主机,您可能需要 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

答案 1 :(得分:0)

我使用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}}"