首页 > 解决方案 > 尝试从文件中获取 IP 并将其用作 Ansible 中的库存

问题描述

我在 test.text 文件中获取 IP 地址列表,我试图从中获取 IP 循环,然后尝试进入组或变量并将其用作主机(dynamic_groups)

下面是我的播放列表

---
- name: provision stack
  hosts: localhost
  connection: local
  gather_facts: no
  serial: 1
  tasks:
    - name: Get Instance IP Addresses From File
      shell: cat /home/user/test.text
      register: serverlist
    - debug: msg={{ serverlist.stdout_lines }}
    - name: Add Instance IP Addresses to temporary inventory groups
      add_host:
        groups: dynamic_groups
        hostname: "{{item}}"
      with_items: serverlist.stdout_lines

- hosts: dynamic_groups
  become: yes
  become_user: root
  become_method: sudo
  gather_facts: True
  serial: 1
  vars:
    ansible_connection: "{{ connection_type }}"
    ansible_ssh_user: "{{ ssh_user_name }}"
    ansible_ssh_private_key_file: "{{ ssh_private_key_file }}"

  tasks:
     .....
     .....

在 playbbok 上运行后,我得到以下错误

TASK [debug] *****************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "192.168.1.10",
        "192.168.1.11",
        "192.168.1.50"
    ]
}

TASK [Add Instance IP Addresses to temporary inventory groups] ***************************************************************************************************************************************************************************
changed: [localhost] => (item=serverlist.stdout_lines)

PLAY [dynamic_groups] *********************************************************************************************************************************************************************************************************************

TASK [Some Command] **********************************************************************************************************************************************************************************************************************
fatal: [serverlist.stdout_lines]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname serverlist.stdout_lines: Name or service not known", "unreachable": true}

我在这里想念什么?

标签: ansible

解决方案


以下是使用变量的正确方法

    - name: Add Instance IP Addresses to temporary inventory groups
      add_host:
        groups: working_hosts
        hostname: "{{item}}"
      with_items: "{{ serverlist.stdout_lines }}"

它应该可以解决您的问题。


推荐阅读