批量检索AWS ssm参数

时间:2018-10-17 16:11:58

标签: node.js amazon-web-services ssm

如何一次从AWS Systems Manager(参数存储)中批量(或多个参数)检索参数?使用aws-sdk,以下是我编写的从参数存储中检索SSM参数的Node.js代码:

      const ssm = new (require('aws-sdk/clients/ssm'))()

      const getSSMKey = async params => {
          const {Parameter: {Value: APIKey}} = await ssm.getParameter(params).promise()
          return APIKey
    }

    const [param1, param2, param3] = await Promise.all([
      getSSMKey({ Name: '/data/param/PARAM1', WithDecryption: true }),
      getSSMKey({ Name: '/data/param/PARAM2', WithDecryption: true }),
      getSSMKey({ Name: '/data/param/PARAM3', WithDecryption: true })
    ])
    console.log(param1, param2, param3)

但是使用此代码,我正在发送3个请求以获取3个参数,这在大量参数的情况下效率低下。有什么方法可以在一个请求中检索多个参数。如果ssm.getParameters()是执行此操作的方法,请举一个示例(特别是该方法的参数)。我尝试过,但是什么也没收到。

4 个答案:

答案 0 :(得分:5)

根据AWS documentGetParameter获取一个参数的值,而GetParameters获取多个参数的值。

它们的用法也非常相似。使用GetParameters获取多个值时,请将多个名称作为Names的列表传递,而不要将单个名称作为字符串传递给Name

代码示例,用于在“ us-west-1”区域中获取名为“ foo”和“ bar”的参数:

const AWS = require('aws-sdk');
AWS.config.update({ region: "us-west-1" });

const SSM = require('aws-sdk/clients/ssm');
const ssm = new SSM()
const query = {
    "Names": ["foo", "bar"],
    "WithDecryption": true
}
let param = ssm.getParameters(query, (err, data) => {
    console.log('error = %o', err);
    console.log('raw data = %o', data);
})

答案 1 :(得分:2)

最后它对我有用。以下是代码:

        const ssmConfig = async () => {
          const data = await ssm.getParameters({ Names: ['/data/param/PARAM1', '/data/param/PARAM2', '/bronto/rest//data/param/PARAM3'],
WithDecryption: true }).promise()
          const config = {}
          for (const i of data.Parameters) {
            if (i.Name === '/data/param/PARAM1') {
              config.param1 = i.Value
            }
            if (i.Name === '/data/param/PARAM2') {
              config.rest.clientId param2 = i.Value
            }
            if (i.Name === '/data/param/PARAM3') {
              config.param3 = i.Value
            }
          }
          return config
        }

答案 2 :(得分:0)

这就是我从特定路径检索所有参数的过程。

**your SSM function  client :**
'use strict';
const SSM = require('aws-sdk/clients/ssm');
let ssmclient;
module.exports.init = () => {
    const region = process.env.REGION === undefined ? 'us-east-1' : process.env.REGION ;
    ssmclient = new SSM({region: region});
}
module.exports.getParameters = async (path) => {
    try {
        let params = {
            Path: path,
            WithDecryption: true
        };
        let allParameters = [];
        let data =  await ssmclient.getParametersByPath(params).promise();
        allParameters.push.apply(allParameters, data.Parameters);
        while(data.NextToken) {
            params.NextToken = data.NextToken;
            data =  await ssmclient.getParametersByPath(params).promise();
            allParameters.push.apply(allParameters, data.Parameters);
        }
        return allParameters;
    } catch (err) {
        return Promise.reject(err);
    }
}
calling this client:

const ssm = require("yourssmclinet");
ssm.init();
// you call only once to retrieve everything which falls under /data/param
const parameters = await getParameters("/data/param");
//from here you can fetch parameters['what ever needed'].

答案 3 :(得分:0)

从本质上讲,您有两个选择来批量获取参数。

一种是@ user1032613提供的方法,另一种是使用内置函数getParametersByPath()。

使用以下三种方法的节点中的Lambda代码示例如下所示。每种方法可以采用不同的参数,例如,可以创建过滤器的路径等,以获取所需的确切值,请参见the documentation

'use strict';
const AWS = require('aws-sdk');
const SSM = new AWS.SSM();

exports.handler = async (event) => {
    //Example get single item
    const singleParam = { Name: 'myParam' };
    const getSingleParam = await SSM.getParameter(singleParam).promise();

    //Example: Get Multiple values
    const multiParams = {
        Names: [ 'myParam1', 'myParam2', 'myParam3' ],
        WithDecryption: true
    };

    const getMultiParams = await SSM(multiParams).promise();

    //Example: Get all values in a path
    const pathParams = { Path: '/myPath/', WithDecryption: true };
    const getPathParams = await SSM.getParametersByPath(pathParams).promise();

    return 'Success';
};

请记住,您也可以使用环境变量。例如,您可以这样编写singleParam:

const singleParam = { Name: process.env.PARAM }

这样,您就可以拥有根据阶段从DEV,PROD等提取代码的代码。