如何从此 AWS SecretsManager JSON 对象中提取字段?

How to extract fields from this AWS SecretsManager JSON Object?

我正在使用 AWS Secrets Manager 来保护我的 REST API 的数据库积分。我正在使用 AWS Lambda、API 网关和 RDS (MySQL)。以下是我如何获得它们。

// Load the AWS SDK
var AWS = require('aws-sdk'),
    region = "us-east-1",
    secretName = "test-secret",
    secret,
    decodedBinarySecret;

// Create a Secrets Manager client
var client = new AWS.SecretsManager({
    region: region
});

// In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
// See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
// We rethrow the exception by default.
exports.handler = (event, context, callback) => {
    client.getSecretValue({
        SecretId: secretName
    }, function(err, data) {
        if (err) {
            throw err
        } else {
            // Decrypts secret using the associated KMS CMK.
            // Depending on whether the secret is a string or binary, one of these fields will be populated.
            if ('SecretString' in data) {
                secret = data.SecretString;
            } else {
                let buff = new Buffer(data.SecretBinary, 'base64');
                decodedBinarySecret = buff.toString('ascii');
            }
        }
// Your code goes here. 
        console.log(secret);
    });
};

下面是输出

INFO    {"username":"***","password":"***","engine":"mysql","host":"***.***.us-east-1.rds.amazonaws.com","port":3306,"dbname":"***","dbInstanceIdentifier":"***"}

我试过如下提取密码

let pass = secret.password;
        console.log(pass);

给出了以下内容

INFO    undefined

如何提取 passwordusernamedatabasename 等字段?

此输出是一个 JSON 对象文字,因此您可以使用以下格式访问每个对象:

secret.password

const secret= {"username":"yourusername","password":"Pa$$w0rd","engine":"mysql","host":"***.***.us-east-1.rds.amazonaws.com","port":3306,"dbname":"***","dbInstanceIdentifier":"***"};
console.log(secret.password);
console.log(secret.username);
document.getElementById("secret").innerHTML = secret.password;
<p>
Your Password is : <span id="secret"></span>
</p>

一开始,你得到 secret 作为 data.SecretString,然后现在 secret 只是一个普通的字符串。在你的情况下,它是一个 JSON 字符串,你必须将你的字符串转换为 JSON 对象,然后你可以轻松地通过属性名称访问信息。

为此,您可以使用 JSON.parse 方法将 json 字符串转换为 json 对象:

var secret = `{"username":"***","password":"***","engine":"mysql","host":"***.***.us-east-1.rds.amazonaws.com","port":3306,"dbname":"***","dbInstanceIdentifier":"***"}
`;

const secretObj = JSON.parse(secret);

console.log(secretObj.host)