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

引用子模块分组创建YANG列表时pyang提示key不存在,问题出在哪?

YANG列表引用分组容器内叶子作为key报错分析

问题场景

我在子模块里定义了一个包含容器的分组:

submodule sub-module {

  belongs-to main-module{
    prefix "sub";
  }

  grouping my-container-group {
    container my-container {
      leaf id {
        type string;
      }
      leaf value {
        type string;
      }
    }
  }
}

然后在主模块中通过这个分组创建列表:

module main-module {

  namespace "http://example-ns";

  prefix "sub";

  include sub-module;

  list my-list {
    key id;
    uses my-container-group;
  }
}

但运行pyang main-module.yang -f tree时抛出错误:

test# pyang main-module.yang -f tree
main-module.yang:10: error: the key "id" does not reference an existing leaf
module: main-module
   +--rw my-list* [id]
      +--rw my-container
         +--rw id?      string
         +--rw value?   string

请问哪里操作错了?

错误原因

列表的key要求引用列表节点的直接子叶子,但你通过uses引入的分组里,id是嵌套在my-container容器内部的,属于列表的孙子节点,不是直接子节点,所以pyang找不到对应的叶子节点。从生成的树状结构也能明确看到层级关系:my-list → my-container → id,不符合key的路径要求。

修复方案

方案一:调整分组结构,让key叶子成为列表直接子节点

修改子模块的分组,把id从容器中移出来,作为分组的直接成员:

submodule sub-module {
  belongs-to main-module{
    prefix "sub";
  }

  grouping my-container-group {
    leaf id {
      type string;
    }
    container my-container {
      leaf value {
        type string;
      }
    }
  }
}

这样id就变成了my-list的直接子节点,能被key id;正确识别。

方案二:使用YANG 1.1的路径式key(保留原有嵌套结构)

如果必须保留容器嵌套的结构,可以用YANG 1.1支持的相对路径指定key。首先要确保主模块声明为YANG 1.1版本,然后修改列表的key定义:

module main-module {
  yang-version 1.1;
  namespace "http://example-ns";
  prefix "sub";

  include sub-module;

  list my-list {
    key "my-container/id";
    uses my-container-group;
  }
}

这种写法需要解析器支持YANG 1.1,旧版本的YANG 1.0不支持路径式key。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:58:13