首页 > 解决方案 > 如何从 Ansible 中控制器的主机文件中获取 IP 地址?

问题描述

我很难弄清楚在我的 Ansible 剧本中设置一个事实,该事实包含我控制器上 /etc/hosts 文件中列出的服务器的 IP 地址。我正在针对需要文件服务器 IP 地址的 Web 服务器运行剧本。我像这样运行命令:

ansible-playbook deploy-webservers.yml -i inventory.ini -l webservers

我的库存文件如下所示:

[fileservers]
prod-fs1.example.com

[webservers]
prod-web1.example.com

[localhost]
127.0.0.1 ansible_connection=local ansible_python_interpreter=/Users/jsmith/.virtualenvs/provision/bin/python

这是剧本:

---
hosts: all
gather_facts: yes
become: yes


pre_tasks:
  - name: get file server's IP address
    command: "grep prod-fs1 /etc/hosts | awk '{ print $1 }'"
    register: fs_ip_addr
    delegate_to: localhost

  - debug: var={{ fs_ip_addr }}

当我运行它时,我得到这个错误:

TASK [get file server's IP address] ****************************************************************************************
fatal: [prod-web1.example.com -> localhost]: FAILED! => {"changed": true, "cmd": ["grep", "prod-fs1", "/etc/hosts", "|", "awk", "{ print $0 }"], "delta": "0:00:00.010303", "end": "2020-03-03 12:24:36.207656", 
"msg": "non-zero return code", "rc": 2, "start": "2020-03-03 12:24:36.197353", "stderr": "grep: |: No such file or directory\ngrep: awk: No such file or directory\ngrep: { print $0 }: 
No such file or directory", "stderr_lines": ["grep: |: No such file or directory", "grep: awk: No such file or directory", "grep: { print $0 }: No such file or directory"], "stdout": "/etc/hosts:45.79.99.99    prod-fs1.example.com    prod-fs1", "stdout_lines": ["/etc/hosts:45.79.99.99    prod-fs1.example.com    prod-fs1"]}


PLAY RECAP ****************************************************************************************************************
prod-web1.example.com : ok=7    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0;

看起来 Ansible 在到达管道符号时解析命令时出现问题。有没有办法解决这个问题?

标签: ansible

解决方案


试试这个。无需委托给本地主机。lookup始终在控制器上运行

    - set_fact:
        fs_ip_addr: "{{ (lookup('file', '/etc/hosts').splitlines()|
                         list|
                         select('search', search_host)|
                         list|
                         first).split().0 }}"
      vars:
        search_host: "prod-fs1"

推荐阅读