如何从Lambda函数访问S3存储桶中的文件

时间:2018-08-20 10:39:23

标签: c# amazon-web-services amazon-s3 aws-lambda

我的S3存储桶中有一个文件,我想通过Lambda函数访问该文件。

当我将此文件的路径传递给方法之一时,出现错误:

  

找不到路径'/var/task/https:/s3.amazonaws.com/TestBucket/testuser/AWS_sFTP_Key.pem”的一部分。

例如:

TestMethod("https://s3.amazonaws.com/TestBucket/testuser/AWS_sFTP_Key.pem")

代码:

public void FunctionHandler(S3Event s3Event, ILambdaContext lambdaContext)
        {
            ConnectionInfo connectionInfo = new ConnectionInfo("xxx.xxx.xx.xxx", "testuser",
                                                   new AuthenticationMethod[]{
            new PrivateKeyAuthenticationMethod("testuser", new PrivateKeyFile[] {
                new PrivateKeyFile("https://s3.amazonaws.com/TestBucket/testuser/AWS_sFTP_Key.pem")})
});

            SftpClient sftpClient = new SftpClient(connectionInfo);
            sftpClient.Connect();
            lambdaContext.Logger.Log(sftpClient.WorkingDirectory);
            sftpClient.Disconnect();
        }

1 个答案:

答案 0 :(得分:1)

您可以使用AWS SDK来从S3读取文件,如下所示,但是我建议使用AWS Certificate ManagerIAM来存储和管理证书和密钥:

PS:确保为lambda函数或存储桶策略分配了适当的角色,以使存储桶能够从GetObject S3

    RegionEndpoint bucketRegion = RegionEndpoint.USWest2;//region where you store your file

    client = new AmazonS3Client(bucketRegion);

    GetObjectRequest request = new GetObjectRequest();

    request.WithBucketName(BUCKET_NAME);//TestBucket
    request.WithKey(S3_KEY);//testuser/AWS_sFTP_Key.pem

    GetObjectResponse response = client.GetObject(request);

    StreamReader reader = new StreamReader(response.ResponseStream);

    String content = reader.ReadToEnd();

更多帮助: