java lambda 上的 Localstack (AWS) 凭证失败

问题描述 投票:0回答:1

此 lambda 的目的是在 kinesis 数据流上插入存储桶内容,代码如下:

package productor;

import software.amazon.awssdk.services.s3.*;
import software.amazon.awssdk.services.kinesis.*;
import software.amazon.awssdk.services.kinesis.model.PutRecordRequest;
import software.amazon.awssdk.services.kinesis.model.PutRecordResponse;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import java.util.*;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import java.io.*;

import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;

public class Productor implements RequestHandler<Map<String,String>, String>{
    static List<String> status_code = new ArrayList<>();
    
    public static Map<String, Object> conexion() {
        //diccionario con conexiones
        Map<String, Object> conexiones = new HashMap<>();

        //Crear clientes de S3
        try {
            String accessKey = "dummy";
            String secretKey = "dummy";
            
            // Crea las credenciales básicas
            AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(accessKey, secretKey);
            // Crear proveedor de credenciales estáticas
            StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(awsCredentials);
            
            S3Client s3_client = S3Client.builder().region(Region.US_EAST_1).credentialsProvider(credentialsProvider).build();           
            KinesisClient kinesis_client = KinesisClient.builder().region(Region.US_EAST_1).credentialsProvider(credentialsProvider).build();
            
            conexiones.put("s3_client", s3_client);
            conexiones.put("kinesis_client", kinesis_client);
            status_code.add("Funcion_conexion.conexion_creada");
            
        } catch (Exception e) {
            status_code.add("Funcion_conexion." + e.getMessage());
        }
        return conexiones;
    }
    
    public static String objeto_fichero(Map<String, Object> localstack) {
        String texto = "None";
        
        try {
            S3Client s3Client = (S3Client) localstack.get("s3_client");
            
            //OLD
            //ResponseInputStream<GetObjectResponse> objeto_bucket1 = s3Client.getObject(b -> b.bucket(bucket_name).key(file));
            
            //Generar peticion a localstack y capturar respuesta
            GetObjectRequest solicitud_fichero = GetObjectRequest.builder().bucket("bucket1").key("contenido.txt").build();
            ResponseInputStream<GetObjectResponse> fichero = s3Client.getObject(solicitud_fichero);
            
            // Usar BufferedReader para leer el contenido de la respuesta
            BufferedReader reader = new BufferedReader(new InputStreamReader(fichero));
            StringBuilder textoBuilder = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                textoBuilder.append(line);
            }
            texto = textoBuilder.toString();
            status_code.add("Funcion_fichero.objeto_extraido");
            
        
        } catch (Exception e) {
            status_code.add("Funcion_fichero." + e.getMessage());
        }
        return texto;
    }
    @SuppressWarnings({ "finally", "unused" })
    public static List<String> subida_kinesis(Map<String, Object> localstack, String objeto) {
        try {
            KinesisClient kinesisClient = (KinesisClient) localstack.get("kinesis_client");
            String streamName = "MiFlujoDeDatos";
            
            //generar peticion y solicitar input al server
            PutRecordRequest solicitud_input = PutRecordRequest.builder().streamName(streamName).data(SdkBytes.fromUtf8String(objeto)).partitionKey("Lorem").build();
            PutRecordResponse response = kinesisClient.putRecord(solicitud_input);
            status_code.add("Funcion_kinesis.objeto_guardado");
            
        } catch (Exception e) {
            status_code.add("Funcion_kinesis." + e.getMessage());
        } finally {
            return status_code;
        }

    }
    
    public String handleRequest(Map<String,String> event, Context context) {
        return subida_kinesis(conexion(),objeto_fichero(conexion())).toString();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(subida_kinesis(conexion(),objeto_fichero(conexion())));
    }

}

我在 aws cli 中创建 lambda:

aws --endpoint-url=http://localhost:4566 lambda create-function --function-name Productor --runtime java17 --handler productor.Productor::handleRequest --role arn:aws:iam::000000000000:role/RolLambda --zip-file fileb://./Productor-0.0.1-SNAPSHOT-jar-with-dependencies.jar

这是 json 输出:

"[Funcion_conexion.conexion_creada, Funcion_conexion.conexion_creada, Funcion_fichero.The AWS Access Key Id you provided does not exist in our records. (Service: S3, Status Code: 403, Request ID: S4DR2KVRMDW7W3AE, Extended Request ID: IiQQx/+M8+j0Y8ZoCdVkxJ+wioZZDEQPIxeFkI/Vzqbx+Bb+71Q92T2kqdkh6NCKwFkx9K7LYdQ=), Funcion_kinesis.The security token included in the request is invalid. (Service: Kinesis, Status Code: 400, Request ID: f7884fc7-2ff4-1f17-aa1f-7f28ff3fbe9f, Extended Request ID: i7Pr7W/hK6q8eisFtF7HkD7sN3C2QhEMvtmk01SHQx7i1LLt184Ua4EpC07Tuic+aL1otTF6hIw9VqnQ8uWhPRaf7g00TEVlx7+cIQJZ4xI=)]"

我无法弄清楚代码有什么问题,可能是凭证问题,但我使用 aws configure 在 localstack 中建立了该凭证。 有什么建议么? 感谢您的阅读

amazon-web-services amazon-kinesis java-17 localstack
1个回答
0
投票

在编写将使用 Java Lambda 运行时 API 部署为 AWS Lambda 函数的 Java Lambda 函数时,您不需要像编写使用 Java SDK 的客户端应用程序时那样需要凭证。

在部署 Lambda 函数时,您可以指定一个有权调用 Lambda 函数使用的 AWS 服务的角色,而不是使用凭证。创建一个有权调用您想要使用 Lambda 函数调用的 AWS 服务的角色,然后在使用 AWS Lambda 控制台部署 Lambda 函数时引用该角色。

要查看使用 Java 构建 Lambda 函数并在其中创建 Lambda 函数使用的角色的实际示例,请参阅 AWS 代码库中的此 Lambda 示例:

使用 AWS 开发工具包通过 Amazon Rekognition 检测图像中的 PPE

© www.soinside.com 2019 - 2024. All rights reserved.