Ansible打印创建主机

时间:2018-01-16 16:39:20

标签: ansible openstack ansible-inventory

我写了一个创建多个虚拟机的Ansible Playbook。 Playbook分为两个文件。 Main.yaml和vars.yaml。它创建虚拟机,似乎运行良好。我没有得到任何错误,所以我认为它成功地将创建的主机添加到库存。我想检查创建的主机是否已添加到Inventory中。如何打印/列出库存的主机?我的目标是在创建的VM上稍后运行脚本。感谢。

**Main.yaml**
#########CREATING VM#########
---
- hosts: localhost
  vars:
    http_port: 80
max_clients: 200
  vars_files:
   - vars.yaml
  tasks:
  - name: create VM
    os_server:
      name: "{{ item.name }}"
      state: present
      image: "{{ item.image }}"
      boot_from_volume: True
      security_groups: ssh
      flavor: "{{ item.flavor }}"
      key_name: mykey
      region_name: "{{ lookup('env', 'OS_REGION_NAME') }}"
      nics:
        - net-name: private
      wait: yes
    register: instances
    with_items: "{{ instance_definitions }}"
 ############################################
  - name: whait 15 seconds
    pause: seconds=15
    when: instances.changed
######DEBUG#################################
  - name: display results
    debug:
      msg: "{{ item }}"
    with_items: "{{ instances.results }}"
############################################
  - name: Add new VM to ansible Inventory
    add_host:
      name: "{{ item.server.name}}"
      ansible_host: "{{item.server.public_v4}}"
      ansible_user: "{{ansible_user}}"
      ansible_ssh_common_args: -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
      groups: just_created
    with_items: "{{ instances.results }}"



**vars.yaml**
---
  instance_definitions:
     - { name: Debian Jessie, image: Debian Jessie 8, flavor: c1.small, loginame: debian }
     - { name: Debian Stretch, image: Debian Stretch 9, flavor: c1.small, loginame: debian }

3 个答案:

答案 0 :(得分:2)

这是magic variables的用途。

您的所有主人都将在列表中:

groups['just_created']

答案 1 :(得分:0)

您可以使用以下方式从剧本打印清单文件的内容:

- debug: msg="the hosts are is {{lookup('file', '/etc/ansible/hosts') }}"

或者,您可以使用以下命令从命令行列出主机:

ansible --list-hosts all

或从剧本中使用此命令:

tasks:
  - name: list hosts
command: ansible --list-hosts all
register: hosts
  - debug:
    msg: "{{hosts.stdout_lines}}"

答案 2 :(得分:0)

以下示例说明了如何创建内存中主机并列出它们。神奇的调味料是add_hosts需要单独播放。

---
 - name: adding host playbook
   hosts: localhost
   connection: local
   tasks:
   - name: add host to in-memory inventory
     add_host:
       name: awesome_host_name
       groups: in_memory

 - name: checking hosts
   hosts: in_memory
   connection: local
   gather_facts: false
   tasks:
     - debug: var=group_names
     - debug: msg="{{ inventory_hostname }}"
     - debug: var=hostvars[inventory_hostname]