无法从具有ansible和group\u vars的变量创建字典

2024-04-18 13:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

形势

在ansible中设置组变量很好。这个上下文每个服务器都有两个双端口NIC(Mellanox)。网络配置通过netplan的group_-vars完成。虽然network:bond0:interfaces像个符咒,network:ethernets:却没有:

## group_vars/my-server-group
Mellanox_1: enp3s0
Mellanox_2: enp5s0
bond0_interfaces:
  - "{{ Mellanox_1 }}"
  - "{{ Mellanox_1 }}d1"
  - "{{ Mellanox_2 }}"
  - "{{ Mellanox_2 }}d1"
interface_no_dhcp:
  dhcp4: no
interface_array: [ '{{ Mellanox_1 }}', '{{ Mellanox_1 }}d1', '{{ Mellanox_2 }}', '{{ Mellanox_2 }}d1' ] 
# ^^^ works, but is useless
interface_array: { '{{ Mellanox_1 }}', '{{ Mellanox_1 }}d1', '{{ Mellanox_2 }}', '{{ Mellanox_2 }}d1' } 
# ^^^ doesn't work
netplan_config_file: /etc/netplan/netplan_ansible.yaml
netplan_configuration:
  network:
    ethernets:
      "{{ interface_array }}"
    bonds:
      bond0:
        interfaces: "{{ bond0_interfaces }}"
        parameters:
          mode:                 802.3ad

结果是:

^{pr2}$

同样,以下操作不起作用并导致错误:recursive loop detected in template string

## group_vars/my-server-group
ethernet_interfaces: |
"{% for interface in bond0_interfaces %}"
"{{ ethernet_interfaces|combine({interface: interface_no_dhcp}) }}"
"{% endfor %}"

问题是:

对于一个数组——就像bond0_接口一样——它在字典中正常工作——它失败了。 据我所知,我需要一个字典而不是一个数组,以便遵循netplan配置准则(described here)。最后应该是:

目标

## /etc/netplan/netplan.yaml (excerpt)
network:
  ethernets:
    enp3s0:
      dhcp4: no
    enp3s0d1:
      dhcp4: no
    enp5s0:
      dhcp4: no
    enp5s0d1:
      dhcp4: no
  bonds:
    bond0:
      interfaces: 
      - enp3s0
      - enp3s0d1
      - enp5s0
      - enp5s0d1
      parameters:
        mode:                 802.3ad

有人有办法吗?在

this thread中,用户holdenweb说:

'Dynamic variable names are almost always a terrible idea'

在这种情况下,这是完全有道理的;—)

我还检查了:


Tags: nogroupnetworkansiblevarsinterfacesinterfaced1
1条回答
网友
1楼 · 发布于 2024-04-18 13:25:39

我有个解决办法。我可以建议使用我的Ansible角色linux_postinstall?任务netplan可以满足您的需要。诀窍是过滤项目.conftemplate

{{ item.conf | from_yaml | to_nice_json }}

下面是创建以太网络和键的测试。我还没有用这些配置文件测试netplan。基督教青年会。example也适用于组成员。在

>;猫计划.netyml

^{pr2}$

>;ansible剧本网络计划.yml-网络计划

>;猫/刮擦/91-以太网.yaml

# Ansible managed
network:
  version: 2
  renderer: networkd
  ethernets:
    {
    "enp3s0": {
        "dhcp4": false
    }, 
    "enp3s0d1": {
        "dhcp4": false
    }, 
    "enp5s0": {
        "dhcp4": false
    }, 
    "enp5s0d1": {
        "dhcp4": false
    }
}

>;猫/刮擦/92-债券.yaml

# Ansible managed
network:
  version: 2
  renderer: networkd
  bonds:
    {
    "bond0": {
        "interfaces": [
            "enp3s0", 
            "enp3s0d1", 
            "enp5s0", 
            "enp5s0d1"
        ], 
        "parameters": {
            "mode": "802.3ad"
        }
    }
}

相关问题 更多 >