获取 Ansible 控制机 IP 地址的最佳方式 [英] Best way to get the IP address of the Ansible control machine

查看:40
本文介绍了获取 Ansible 控制机 IP 地址的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ansible 和 ufw 在我的服务器上设置防火墙.作为 ufw 规则的一部分,我希望允许来自 Ansible 控制机器的 SSH,但不允许来自其他任何地方.我的问题是 - 获取控制机器本身的 IP 地址以便我可以将其纳入规则的最佳方法是什么?

I am using Ansible and ufw to setup a firewall on my servers. As part of the ufw rules I would like to allow SSH from the Ansible control machine, but not from anywhere else. My question is - what is the best way to get the IP address of the control machine itself so I can put it into the rule?

我知道我可以使用 facts 获取我正在运行剧本的机器的 IP 地址,但我没有看到任何简单的方法可以为运行 ansible 的机器自动获取它.

I'm aware that I can use facts to get the IP address of the machine I am running the playbook on, but I don't see any easy way to get it automatically for the machine that is running ansible.

如果可能的话,我想避免添加一个新变量来表示这一点,因为如果可以自动发现它会很好,但如果这是唯一已知的最佳方法,那么我会这样做.

I'd like to avoid adding a new variable to represent this if possible since it would be nice if it was automatically discoverable, though if that's the only known best way to do it then I will just do that.

我发现了这个重复的问题这和我的一样,但是它也没有得到答复,因此将其保留一段时间.

I found this duplicate question which is the same as mine, however it also is unanswered so will leave this open for a bit.

推荐答案

{{ ansible_env['SSH_CLIENT'].split() | first }}

有效,但您必须从默认用户收集有关连接变量的事实,所以八点:

works, but you have to gather facts about connection variables from default user, so eighter:

  • 在剧本级别设置 «gather_facts: yes» 和 not «become: yes»
  • 更可靠:运行 «setup» 任务(没有 «become: yes» 并且在使用 «ansible_env» 之前 - 在 «pre_tasks» 部分更好).
  • Set «gather_facts: yes» and not «become: yes» on playbook level
  • More reliable: run «setup» task (without «become: yes» and before this «ansible_env» usage — better on «pre_tasks» section).

如果您使用 «become» 运行 «gather/setup»,您稍后将获得 «一个或多个未定义的变量:'dict object' 没有属性 'SSH_CLIENT'»(这是因为 sudoed «setup» 只能捕获小变量集).

If you run «gather/setup» with «become», you will later get «One or more undefined variables: 'dict object' has no attribute 'SSH_CLIENT'» (this is becase sudoed «setup» can catch only small set of variables).

这篇关于获取 Ansible 控制机 IP 地址的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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