You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible中定义端口哈希并复用配置应用与防火墙规则?

解决ARK集群端口集中配置与引用的Ansible方案

我明白你想要通过集中定义端口哈希来减少配置重复的需求,这在Ansible里完全可以实现,核心是用Jinja2变量引用来直接调用你定义的集中配置,下面是具体的实现方法:

1. 正确定义集中端口哈希

首先在你的host_vars/hostXX.yaml里先定义好所有端口的集中配置,和你设想的结构一致:

ark_cluster_ports:
  theisland:
    game_port: 7777
    query_port: 27015
    rcon_port: 27020

2. 在cluster_nodes中引用端口变量

在cluster_nodes的network字段里,直接用Jinja2的{{ 变量路径 }}语法引用即可,YAML会自动解析这些变量:

cluster_nodes:
  - map: TheIsland
    user: theisland
    network:
      game_port: "{{ ark_cluster_ports.theisland.game_port }}"
      query_port: "{{ ark_cluster_ports.theisland.query_port }}"
      rcon_port: "{{ ark_cluster_ports.theisland.rcon_port }}"

3. 在iptables_rules中引用端口变量

防火墙规则里的destination_port字段同样可以用变量引用,写法和上面一致:

iptables_rules:
  - rule:
      chain: INPUT
      interface: enp98s0f0
      protocol: tcp
      destination_port: "{{ ark_cluster_ports.theisland.rcon_port }}"
      jump: ACCEPT
  - rule:
      chain: INPUT
      interface: enp98s0f0
      protocol: udp
      destination_port: "{{ ark_cluster_ports.theisland.game_port }}"
      jump: ACCEPT
  - rule:
      chain: INPUT
      interface: enp98s0f0
      protocol: udp
      destination_port: "{{ ark_cluster_ports.theisland.query_port }}"
      jump: ACCEPT

为什么你之前的方法没成功?

  • 锚点与合并运算符:锚点适合复用整个YAML节点(比如重复的规则结构),但你需要的是引用哈希里的单个值,锚点无法直接提取单个字段,所以不适用。
  • 字典lookup:如果用lookup('dict', ...)的方式,你需要正确处理返回的键值对,而且对于单个值的引用来说,直接用变量路径比lookup更简单直接,没必要绕弯子。

进阶优化:多节点场景的循环生成

如果之后你要添加更多集群节点,可以用Ansible的循环功能自动生成cluster_nodes和iptables_rules,避免手动重复编写。比如:

# 先定义所有节点的端口
ark_cluster_ports:
  theisland:
    map: TheIsland
    user: theisland
    game_port: 7777
    query_port: 27015
    rcon_port: 27020
  scorchedearth:
    map: ScorchedEarth
    user: scorchedearth
    game_port: 7778
    query_port: 27016
    rcon_port: 27021

# 用循环生成cluster_nodes
cluster_nodes: "{{ ark_cluster_ports | dict2items | map(attribute='value') | list }}"

# 用循环生成iptables规则(UDP游戏/查询端口 + TCP远程管理端口)
iptables_rules:
  # 生成UDP端口规则
  - "{{ ark_cluster_ports | dict2items | subelements('value', skip_missing=True) | selectattr('1', 'in', ['game_port', 'query_port']) | map('combine', {'rule': {'chain': 'INPUT', 'interface': 'enp98s0f0', 'protocol': 'udp', 'jump': 'ACCEPT'}}) | list }}"
  # 生成TCP远程管理端口规则
  - "{{ ark_cluster_ports | dict2items | map('attribute', 'value.rcon_port') | map('combine', {'rule': {'chain': 'INPUT', 'interface': 'enp98s0f0', 'protocol': 'tcp', 'jump': 'ACCEPT'}}) | list }}"

这样新增节点时只需要在ark_cluster_ports里添加配置,其他部分会自动生成,非常高效。

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 18:07:50