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

查看:130
本文介绍了如何使用 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.

希望像这样保存数据:

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天全站免登陆