ansible - 如何从 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 在到达管道符号时解析命令时出现问题。有没有办法解决这个问题?
解决方案
试试这个。无需委托给本地主机。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"
推荐阅读
- postgresql - 突然有 sql_error_code = 42601 STATEMENT: SET statement_timeout TO ?在日志中
- python - 需要帮助加入字典项目并删除换行符和多个空格和特殊字符
- reactjs - 将 React 连接到 Google Cloud Platform
- python - 将标签数组添加到 xml 根目录
- macos - 在 Mac 中执行 Shell 文件功能
- python - 读取多个 CSV 并根据文件名 python 中的年份将这些 CSV 合并到单独的文件中
- javascript - 在 HTML 和 JavaScript 中使用两种颜色标度着色
- javascript - 如何使用钩子在本机反应中保存/下载生成二维码?
- sas - 呼叫模块 SAS 企业指南
- docker - 在 WSL2 上运行 Docker 的僵尸文件夹起死回生