如何在 Ansible 中从控制器的主机文件中获取 IP 地址?



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

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 directoryngrep: awk: No such file or directoryngrep: { 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似乎在解析命令时遇到问题。有办法解决这个问题吗?

试试这个。无需委托给localhost。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"

代码可以简化一点。请注意,search_host是一个变量

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

最新更新