如何使用Ansible获取主机IP和主机名 [英] How to get host IP and hostname using Ansible

查看:917
本文介绍了如何使用Ansible获取主机IP和主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个任务,该任务将获取清单中的主机目标IP地址和主机名,然后将其保存到本地目录中的文件中.

I am trying to create a task that will get the host target IP address and host-name that are in the inventory then save it to a file in the local directory.

很乐意像这样保存数据:

Would love to save the data like this:

hostname:ip-address

从哪里开始?

推荐答案

我建议使用" delegate_to ",我在我的计算机上尝试了该方法,然后它可以正常工作.我将第一步删除该文件(如果存在),以便可以多次执行.这是一个非常快速的示例,我建议对路径使用变量,等等.但是我认为您可以理解

I would suggest using"delegate_to", I tried that on my computer and it worked properly. I put the first step to delete the file if it exists so it can be executed multiple times. This is a very fast example, I suggest to use variables for the path, etc. But I think you can get the idea

---
- hosts: your_inventory

  tasks:
    - name: delete the file if exists
      file:
        path: /home/yourpath/host_ip.txt
          state: absent
      delegate_to: localhost
    - name: get data to a file
      lineinfile:
        dest: /home/yourpath/host_ip.txt
        create: yes
        line: "{{hostvars[inventory_hostname].ansible_hostname}}:{{hostvars[inventory_hostname].ansible_default_ipv4.address}}"
      delegate_to: localhost

这篇关于如何使用Ansible获取主机IP和主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆