2

我们有从 libsonnet 导入的数组

{
  "volumes": [
    {
      "emptyDir": {},
      "name": "grafana-storage"
    },
    {
      "configMap": {
        "name": "grafana-dashboard-apiserver"
      },
      "name": " grafana-dashboard-apiserver"
    }
  ]
}

我想替换这个元素:

    {
      "emptyDir": {},
      "name": "grafana-storage"
    },

与这个(相同name):

    {
      "name": "grafana-storage",
      "persistentVolumeClaim": {
        "claimName": "product-nfs"
      }

预期输出:

{
  "volumes": [
    {
      "configMap": {
        "name": "grafana-dashboard-apiserver"
      },
      "name": " grafana-dashboard-apiserver"
    },
    {
      "name": "grafana-storage",
      "persistentVolumeClaim": {
        "claimName": "product-nfs"
      }
    }
  ]
}

“附加”很容易,但是如何删除现有的

例子:

local x = {volumes: [
  {emptyDir: {}, name: 'grafana-storage' },
  {configMap: {name:  'grafana-dashboard-apiserver'
}, name: ' grafana-dashboard-apiserver'},]};

x 
+ {volumes+: [{name: 'grafana-storage',persistentVolumeClaim: {claimName:'product-nfs'}}]}

先谢谢了~

4

1 回答 1

1

在派生/重载方面,jsonnet使用地图(又名“对象”、“字典”、“哈希”)要容易得多,策略是:1)转换为地图,2)覆盖,3)转换回大批。

下面的代码片段实现了它:

local main_obj = {
  volumes: [
    {
      emptyDir: {},
      name: "grafana-storage",
    },
    {
      configMap: {
        name: "grafana-dashboard-apiserver",
      },
      name: "grafana-dashboard-apiserver",
    },
  ],
};

local obj_overrides = {
  volumes: [
    {
      name: "grafana-storage",
      persistentVolumeClaim: { claimName: "product-nfs" },
    },
  ],
};

// Convert to map for easier overloading, assumes all array elements are maps having "name" field
local toNamedMap(array) = { [x.name]: x for x in array };

// Convert back to array
local toNamedArray(map) = [{ name: x } + map[x] for x in std.objectFields(map)];

toNamedArray(toNamedMap(main_obj.volumes) + toNamedMap(obj_overrides.volumes))
于 2020-04-29T11:19:12.477 回答