Docs 菜单
Docs 主页
/ /
Atlas
/

自定义 Atlas CLI 输出

在此页面上

  • Go 模板
  • json-path 输出类型

您可以使用 Go 模板或 JSON 路径自定义 Atlas CLI 输出字段和格式,这样可以更轻松地根据 Atlas CLI 的输出实现流程自动化。

您可以在任何 Atlas CLI 命令中或通过单独的文件指定 Go 模板。 要了解有关 Go 模板的详情,请参阅 包模板 。要了解每个响应可用的类型和属性,请参阅 Atlas 类型。

您可以使用命令并使用--output-o选项来指定模板:

--output|-o go-template="{{<template>}}"

或者,您可以使用--output-o选项通过文件指定模板:

--output|-o go-template-file="<path-to-template-file>"

以下命令使用模板检索指定组织中的项目数量:

atlas projects ls --orgId 5ab5cedf5g5h5i5j5kl12mn4 -o go-template="Count: {{.TotalCount}}"

上述命令会返回以下输出:

Count: 2

以下 atlas clusters describe命令使用该模板检索名为getStarted的 Atlas 集群的连接字符串。它使用默认配置文件访问 Atlas。

atlas clusters describe getStarted -o go-template="Parse: {{.SrvAddress}}"

上一个命令会返回一个类似于以下内容的字符串:

Parse: mongodb+srv://getstarted.example.mongodb.net

您可以使用MongoDB Shell mongosh ,通过 srvAddress连接string连接到 getStarted 集群。 此示例使用上一个命令为用户名为 User1 的用户返回的连接string 。

mongo "mongodb+srv://getstarted.example.mongodb.net" --username User1 --password ChangeThisPasswordToSomethingSecure

例如,考虑以下名为template.tmpl的文件:

Projects: {{range .Results}}{{.ID}} {{end}}

以下命令使用template.tmpl文件检索指定组织中项目的 ID:

atlas projects ls --orgId 5ab5cedf5g5h5i5j5kl12mn4 -o go-template-file="template.tmpl"

上述命令会返回以下输出:

Projects: 5e2211c17a3e5a48f5497de3 5f455b39749bea5fb575dccc

json-path输出类型将命令的结果限制为您指定的字段。

向命令添加--output选项时,可以指定类型json-path 。 您必须为json-path提供一个表达式,以根据您的结果进行评估,这意味着您必须了解命令返回的json字段。

<command> --output|-o json-path='$<expression>'

json-path 表达式是指 Atlas CLI 命令返回的 JSON元素。 $字符表示根元素,通常是对象或数组。

有关有效字符及其功能的列表,请参阅 JSONPath 表达式。

在以下示例中,用户使用 atlas organizations apiKeys list 检索其 API 密钥。json-path表达式将输出限制为第一个键的desc字段,而不是返回整个键列表。

atlas organizations apikeys list --output json-path='$[0].desc'
> owner_key

使用--output json 运行相同的命令会返回来自 API 的完整 JSON 元素。为了使用json-path对其进行操作,了解命令返回的JSON结构非常重要。

使用以下完整 JSON 输出作为参考,带有表达式--output json-path$[0].desc 查找并仅返回值"owner_key"

[ //``$`` represents the outer array.
{ // ``[0]`` refers to the first element in the array (using a 0-based index).
"id": "60e736a95d585d2c9ccf2d19",
"desc": "owner_key", //``.desc`` refers to the ``desc`` field of that element.
"roles": [
{
"orgId": "5d961a949ccf64b4e7f53bac",
"roleName": "ORG_OWNER"
}
],
"privateKey": "********-****-****-c4e26334754f",
"publicKey": "xtfmtguk"
},
{
"id": "d2c9ccf2d1960e736a95d585",
"desc": "member_key",
"roles": [
{
"orgId": "5d961a949ccf64b4e7f53bac",
"roleName": "ORG_MEMBER"
}
],
"privateKey": "********-****-****-c4e26334754f",
"publicKey": "vfgcttku"
},
]

在以下示例中,用户使用 atlas organizations apiKeys list 检索其 API 密钥。json-path表达式使用id d2c9ccf2d1960e736a95d585将输出限制为特定JSON对象的desc字段。

atlas organizations apikeys list --output json-path='$[? @.id=="d2c9ccf2d1960e736a95d585"].desc'
> member_key

在以下示例中,用户使用Atlas privateEndpoints Amazon Web Services describe检索私有端点的信息。 json-path表达式将输出限制为根元素的status字段。

atlas privateendpoints aws describe 601a4044da900269480a2533 --output json-path='$.status'
> WAITING_FOR_USER

后退

环境变量

来年

配置遥测