如何在用 kotlin 编写的 lambda 函数中设置 AWS 密钥?



我正在尝试在我的lambda函数中设置AWS密钥。我需要在 lambda 函数中访问 AWS SES,以便发送电子邮件。我尝试在 lambda 控制台中设置环境变量,但找不到凭据。有没有办法以编程方式设置凭据?

fun sendEmail(){
try{
val client = AmazonSimpleEmailServiceClientBuilder.standard()
.withRegion(Regions.US_EAST_1).build()

val request = SendEmailRequest()
.withDestination(Destination().withToAddresses(EMAIL_TO))
.withMessage(Message().withBody(Body().withHtml(Content().withCharset("UTF-8").withData(EMAIL_HTML_BODY))
.withText(Content().withCharset("UTF-8").withData(EMAIL_TEXT_BODY)))
.withSubject(Content().withCharset("UTF-8").withData(EMAIL_SUBJECT)))
.withSource(EMAIL_FROM)
.withConfigurationSetName(EMAIL_CONFIGSET)
client.sendEmail(request)
println("Email sent")
}catch (e: Exception){
println("Email failed to send with error: ${e.message}")
println(e.printStackTrace())
}
}
  • 我认为好的做法是拥有一个 iam 角色(您的 lambda 已经拥有该角色(并为该角色提供调用 Amazon SES 的适当访问权限。
  • 例如,仅出于初始测试目的,将以下策略arn:aws:iam::aws:policy/AmazonSESFullAccess附加到您的 lambda iam 角色。以后,您可以限制为仅特定操作。
  • 策略 json 如下所示
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ses:*"
],
"Resource": "*"
}
]
}

我能够使用BasicAWSCredentials(AWS_ACCESS_KEY,AWS_SECRET_KEY(设置凭据

fun sendEmail(){
try{
BasicAWSCredentials(AWS_ACCESS_KEY,AWS_SECRET_KEY)
val client = AmazonSimpleEmailServiceClientBuilder.standard()
.withRegion(Regions.US_EAST_1).build()

val request = SendEmailRequest()
.withDestination(Destination().withToAddresses(EMAIL_TO))
.withMessage(Message().withBody(Body().withHtml(Content().withCharset("UTF-8").withData(EMAIL_HTML_BODY))
.withText(Content().withCharset("UTF-8").withData(EMAIL_TEXT_BODY)))
.withSubject(Content().withCharset("UTF-8").withData(EMAIL_SUBJECT)))
.withSource(EMAIL_FROM)
.withConfigurationSetName(EMAIL_CONFIGSET)
client.sendEmail(request)
println("Email sent")
}catch (e: Exception){
println("Email failed to send with error: ${e.message}")
println(e.printStackTrace())
}
}

相关内容

  • 没有找到相关文章

最新更新