通过ansible setup模块收集linux主机信息,如果在hosts文件中自定义了字段,如何通过setup收集该信息?
时间: 2024-04-27 17:24:38 浏览: 207
可以在`hosts`文件中使用`ansible_host`、`ansible_user`、`ansible_port`等字段来自定义主机信息,然后使用`setup`模块收集这些自定义的主机信息。
以下是一个例子,展示如何在`hosts`文件中自定义字段,并使用`setup`模块收集这些字段:
```
[webserver]
web1 ansible_host=10.0.0.1 ansible_user=ubuntu ansible_port=22
[database]
db1 ansible_host=10.0.0.2 ansible_user=root ansible_port=2222
```
在这个例子中,我们定义了两个主机`web1`和`db1`,并且使用`ansible_host`、`ansible_user`、`ansible_port`字段来自定义主机信息。
然后,我们可以使用以下的Ansible Playbook来收集这些自定义的主机信息:
```yaml
- name: Collect host facts
hosts: all
tasks:
- name: Collect host facts
setup:
```
在这个Playbook中,我们通过`setup`模块收集所有主机的信息,包括定义在`hosts`文件中的自定义信息。
收集完主机信息后,我们可以使用`ansible_host`、`ansible_user`、`ansible_port`等变量在后续任务中连接到主机,例如:
```yaml
- name: Install nginx
hosts: webserver
become: yes
tasks:
- name: Install nginx
apt:
name: nginx
state: present
become_user: "{{ ansible_user }}"
become_method: sudo
ansible_ssh_port: "{{ ansible_port }}"
ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
```
在这个例子中,我们使用`ansible_user`、`ansible_port`变量连接到`webserver`主机,并以`sudo`权限安装`nginx`软件包。
阅读全文
相关推荐















