更新lambda函数的环境变量使用API。

huangapple go评论60阅读模式
英文:

Update lambda function environment variables using api

问题

我收到错误消息 {message: '缺少身份验证令牌'} 。
如何修复这个问题?

如何提供正确的身份验证?

英文:

I got error {message: 'Missing Authentication Token'} .
how can i fix issue ?

const AWS_REGION = 'myREGION';
const FUNCTION_NAME = 'myfn';
const ACCESS_KEY = 'myACCESS_KEY';
const SECRET_KEY = 'mySECRET_KEY';

const updateEnvironmentVariables = async () => {
const credentials = `${ACCESS_KEY}:${SECRET_KEY}`;

  const mybody = JSON.stringify({
  "environment": {
    "Variables": {
      "API_KEY": "abc123",
      "DB_URL": "https://my.com/db"
    }
  }
});

    const response = await fetch(`https://lambda.${AWS_REGION}.amazonaws.com/2015-03-31/functions/${FUNCTION_NAME}/configuration`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': credentials,
      },
      body: mybody,
    }).then((v)=>v.json());
    console.log(response)
};

how i provide correct Authentication?

答案1

得分: 0

不要回答我要翻译的问题。以下是要翻译的内容:

"发送凭证作为请求头的一部分是不足够的。要直接访问AWS API,您需要使用您的凭证对请求进行签名

话虽如此,我强烈建议使用AWS JavaScript SDK,因为它会为您处理所有底层工作。

在您的示例中使用UpdateFunctionConfigurationCommand 会类似于以下方式:

import { LambdaClient, UpdateFunctionConfigurationCommand } from "@aws-sdk/client-lambda";
    
const AWS_REGION = '我的区域';
const FUNCTION_NAME = '我的函数名';
const ACCESS_KEY = '我的访问密钥';
const SECRET_KEY = '我的秘密密钥';

const client = new LambdaClient({ 
  region: AWS_REGION,
  credentials: {
    accessKeyId: ACCESS_KEY,
    secretAccessKey: SECRET_KEY
  }
});

const config = JSON.stringify({
  "environment": {
    "Variables": {
      "API_KEY": "abc123",
      "DB_URL": "https://我的.com/db"
    }
  }
})

const command = new UpdateFunctionConfigurationCommand({
  ...JSON.parse(config),
  FunctionName: FUNCTION_NAME,
});

const response = await client.send(command);

console.log(response)

注意:请确保不要将包含凭证的任何文件提交到源代码存储库,例如git。您可以使用本地AWS配置文件、环境变量或秘密存储来代替。

英文:

It's not enough to send the credentials as part of the request header. To directly access the AWS API, you need to sign the request with your credentials.

Having that said, I would strongly recommend using the AWS SDK for JavaScript instead because it takes care of all the low-level work for you.

Using the UpdateFunctionConfigurationCommand in your example would look something like this:

import { LambdaClient, UpdateFunctionConfigurationCommand } from "@aws-sdk/client-lambda";
    
const AWS_REGION = 'myREGION';
const FUNCTION_NAME = 'myfn';
const ACCESS_KEY = 'myACCESS_KEY';
const SECRET_KEY = 'mySECRET_KEY';

const client = new LambdaClient({ 
  region: AWS_REGION,
  credentials: {
    accessKeyId: ACCESS_KEY,
    secretAccessKey: SECRET_KEY
  }
});

const config = JSON.stringify({
  "environment": {
    "Variables": {
      "API_KEY": "abc123",
      "DB_URL": "https://my.com/db"
    }
  }
})

const command = new UpdateFunctionConfigurationCommand({
  ...JSON.parse(config),
  FunctionName: FUNCTION_NAME,
});

const response = await client.send(command);

console.log(response)

Note: Please make sure to not commit any files to a source code repository, e.g. git, that contain credentials. You can use a local AWS profile, environment variables, or a secret store instead.

答案2

得分: -1

以下是翻译好的部分:

错误消息通常表示您的请求未经身份验证。在 AWS 中,大多数经过身份验证的请求都使用 AWS Signature Version 4 进行签名。您当前传递的身份验证('Authorization':credentials,)无效,因为它包含访问密钥和秘密密钥拼接在一起。

AWS SDK 和 CLI 会为您处理请求签名,但如果您正在进行手动 API 调用(似乎您正在这样做),则需要手动进行签名。AWS Signature Version 4 签名过程有点复杂。您可以在此处查看完整详情:签名

然而,与 AWS 资源交互的一种更简单的方式是使用 AWS SDK for JavaScript 在 Node.js 中。以下是如何使用 AWS SDK 更新 AWS Lambda 环境变量的示例:

var AWS = require('aws-sdk');

AWS.config.update({
  region: 'myREGION',
  accessKeyId: 'myACCESS_KEY',
  secretAccessKey: 'mySECRET_KEY'
});

var lambda = new AWS.Lambda();

var params = {
  FunctionName: 'myfn',
  Environment: {
    Variables: {
      'API_KEY': 'abc123',
      'DB_URL': 'https://my.com/db'
    }
  }
};

lambda.updateFunctionConfiguration(params, function(err, data) {
  if (err) console.log(err, err.stack); // 发生错误
  else     console.log(data);           // 成功响应
});

请将 myREGIONmyACCESS_KEYmySECRET_KEY 替换为您的实际值。

在使用以下命令之前,请确保通过 npm 安装 AWS SDK:

npm install aws-sdk

请记住,将 AWS 访问凭据硬编码在代码中并不是一个好的做法。考虑将它们安全地存储在环境变量中,或者在运行在 EC2 实例或 AWS Lambda 上的 IAM 角色中使用它们。

最后,请始终确保您在 AWS IAM 中具有执行所需操作的必要权限。在这种情况下,您将需要 lambda:UpdateFunctionConfiguration 权限。

英文:

The error message you're seeing usually indicates that your request isn't authenticated. In AWS, most authenticated requests are signed with AWS Signature Version 4. The authentication you currently pass ('Authorization': credentials,) isn't valid as it contains the access and secret keys concatenated together.

AWS SDKs and CLI handle request signing for you, but if you're making manual API calls (as it appears you are doing), you'll have to sign them manually. AWS Signature Version 4 signing process is somewhat complex. You can see full details here: Signature

However, a simpler way to interact with AWS resources is to use the AWS SDK for JavaScript in Node.js. Here is how you could update your AWS Lambda environment variables using the AWS SDK:

var AWS = require('aws-sdk');

AWS.config.update({
  region: 'myREGION',
  accessKeyId: 'myACCESS_KEY',
  secretAccessKey: 'mySECRET_KEY'
});

var lambda = new AWS.Lambda();

var params = {
  FunctionName: 'myfn',
  Environment: {
    Variables: {
      'API_KEY': 'abc123',
      'DB_URL': 'https://my.com/db'
    }
  }
};

lambda.updateFunctionConfiguration(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Please replace 'myREGION', 'myACCESS_KEY' and 'mySECRET_KEY' with your actual values.

Please ensure you install AWS SDK via npm before you use it with the command:

npm install aws-sdk

Remember that hardcoding AWS access credentials in the code are not a good practice. Consider storing them securely in environment variables or using IAM roles running on EC2 instances or AWS Lambda.

Lastly, always ensure you have the necessary permissions in AWS IAM to perform the required operations. In this case, you'll need the lambda:UpdateFunctionConfiguration permission.

huangapple
  • 本文由 发表于 2023年6月22日 20:33:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定