Home > Blockchain >  Access S3 from lambda using assume role
Access S3 from lambda using assume role

Time:10-20

I am trying to create a simple infrastructure using terraform.Terraform should create the lambda and s3 bucket, lambda is triggered using API gateway which is again created terraform. I have created a role and assigned that to lambda so that lambda can put objects in s3 bucket. My lambda is written in java, since I am assigning role to lambda to access S3, how do I use that role in my code? I came across another article which suggested accessing S3 using the below code. I assumed the token generation would be taken care of this.

var s3Client = AmazonS3ClientBuilder.standard()
         .withCredentials(InstanceProfileCredentialsProvider(false))
        .withRegion("ap-southeast-2")
        .build()

I am confused as to how to access s3, do I need to use the role created by terraform in my code or is there a different way to access S3 from java code?

CodePudding user response:

You don't need to assume the role inside the Lambda function. Instead, simply configure the Lambda function to assume the IAM role. Or add the relevant S3 policy to the Lambda's existing IAM role.

You don't typically have to supply credentials or region explicitly in this case. Simply use:

AmazonS3 s3Client = new AmazonS3Client();

See the Terraform basic example of creating both an IAM role and a Lambda function, and configuring the Lambda function to assume the configured role.

CodePudding user response:

Jarmods answer is correct that you can configure the role of the Lambda directly - but there are particular use cases where you may need to be first in one account, than the other. If you need to assume a role in the middle of your code, then use the STS functionality of your SDK. STS is the library in the aws sdk that controls assuming a role's credentials through code.

  • Related