如何让Ansible任务从公网IP切换为针对私网IP主机执行?
利用Ansible条件判断适配公网/私网IP场景
当然可以!咱们可以通过Ansible的when条件判断结合ipaddr过滤器,轻松实现根据主机是否存在公网/私网IP来执行对应任务的需求。
完整Playbook示例
- name: 根据IP类型执行对应搜索任务 hosts: all tasks: - name: Search1 - 使用公网IP执行搜索 become: no delegate_to: localhost command: "../home/ev/search.py {{ item }}" register: name with_items: "{{ ansible_all_ipv4_addresses | ipaddr('public') }}" changed_when: false # 仅当主机存在公网IP时执行此任务 when: ansible_all_ipv4_addresses | ipaddr('public') | length > 0 - name: Search2 - 使用私网IP执行搜索 become: no delegate_to: localhost command: "../home/ev/search.py {{ item }}" register: private_name with_items: "{{ ansible_all_ipv4_addresses | ipaddr('private') }}" changed_when: false # 仅当主机存在私网IP时执行此任务 when: ansible_all_ipv4_addresses | ipaddr('private') | length > 0
关键逻辑说明
IP过滤与条件判断
ansible_all_ipv4_addresses | ipaddr('public'):从主机所有IPv4地址中过滤出公网IP| length > 0:判断过滤后的结果是否非空(即主机存在公网IP),满足条件则执行对应任务- 私网IP的判断逻辑同理,只需把
public替换为private
互斥执行的可选调整
如果你的场景中需要公网IP和私网IP任务互斥执行(即有公网就只执行Search1,只有私网才执行Search2),可以修改条件为:- Search1的条件:
when: (ansible_all_ipv4_addresses | ipaddr('public') | length > 0) and (ansible_all_ipv4_addresses | ipaddr('private') | length == 0) - Search2的条件:
when: ansible_all_ipv4_addresses | ipaddr('private') | length > 0
- Search1的条件:
这样就能完美适配VPS、AWS这类以私网IP为主要配置的服务器场景啦!
内容的提问来源于stack exchange,提问作者Evgeni
相关产品推荐
相关产品推荐

