您可以使用 Go 模板或 JSON 路径自定义 Atlas CLI 输出字段和格式,这样可以更轻松地根据 Atlas CLI 的输出实现流程自动化。
Go 模板
您可以在任何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集群连接string
以下Atlas clusters describe 命令使用该模板检索名为 的 集群的连接string AtlasgetStarted。它使用默认配置文件访问 Atlas。
atlas clusters describe getStarted -o go-template="Parse: {{.SrvAddress}}"上一个命令会返回一个类似于以下内容的string :
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 5f455b39749bea5fb575dcccjson-path 输出类型
json-path输出类型将命令的结果限制为您指定的字段。
使用
向命令添加--output选项时,可以指定类型json-path 。 您必须为json-path提供一个表达式,以根据您的结果进行评估,这意味着您必须了解命令返回的json字段。
语法
<command> --output|-o json-path='$<expression>'json-path 表达式是指 Atlas CLI 命令返回的 JSON 元素。$ 字符表示根元素,通常是对象或数组。
有关有效字符及其功能的列表,请参阅 JSONPath 表达式。
示例
返回列表中第一个API密钥的描述
在以下示例中,用户使用 atlas organizations apiKeys list 检索其 API 密钥。json-path 表达式将输出限制为第一个密钥的 desc 字段,而不是返回整个密钥列表。
atlas organizations apikeys list --output json-path='$[0].desc'> owner_key使用--output json 运行相同的命令会返回来自 API 的完整 JSON 元素。必须了解命令返回的 JSON 结构,以便使用 json-path 对其进行操作。
以下完整的 JSON 输出为参考,具有表达式 $[0].desc 的 --output json-path 只会查找并返回值 "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" },]返回列表中特定API密钥的说明
在以下示例中,用户使用 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