在AWS Amplify中添加环境变量需要使用AWS密钥管理服务(KMS)和AWS系统管理服务(SSM)。以下是通过控制台添加环境变量的步骤:
以下示例代码显示如何在应用程序中访问环境变量:
import AWS from 'aws-sdk';
const ssm = new AWS.SSM();
async function getEnvironmentVariables() {
try {
const params = {
Names: ['MY_ENV_VAR'], // Replace with your environment variable name
WithDecryption: true // Decrypts the environment variable value
};
const result = await ssm.getParameters(params).promise();
const envVars = result.Parameters.reduce((env, param) => {
env[param.Name] = param.Value;
return env;
}, {});
return envVars;
} catch (err) {
console.log(err);
}
}
// Usage example
getEnvironmentVariables().then((envVars) => {
console.log(envVars.MY_ENV_VAR);
});