Get credential provider to invoke AWS Lambda functions when the JAVA application is hosted in AWS EC2 instance

Viewed 1181

I want to invoke AWS Lambda functions in my java application using aws-java-sdk. It was possible when

  1. Access Key and Security Key are given in awsCredentials
  2. ARN and payload are given in invokeRequest

as in the following code.

BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);

AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
        .withCredentials(credentialsProvider)
        .build();

InvokeRequest invokeRequest = new InvokeRequest()
        .withFunctionName(resourceName)
        .withPayload(payload)
        .withInvocationType(InvocationType.RequestResponse);

InvokeResult invokeResult = awsLambda.invoke(invokeRequest);

According to AWS documentation https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/java-dg-roles.html, if my java application is hosted in Amazon EC2 instance, it's more convenient to grant secure access to AWS resources from Amazon EC2 instance rather than manually entering access keys. To try that I have implemented the following modified code in my java application hosted in an EC2 instance.

InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.getInstance();

AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
        .withCredentials(credentialsProvider)
        .build();

InvokeRequest invokeRequest = new InvokeRequest()
        .withFunctionName(resourceName)
        .withPayload(payload)
        .withInvocationType(InvocationType.RequestResponse);

InvokeResult invokeResult = awsLambda.invoke(invokeRequest);

But it's returning following error

com.amazonaws.SdkClientException: The requested metadata is not found at http://169.254.169.254/latest/meta-data/iam/security-credentials/

I want to know;

  1. whether my approach is right to generate credentials
  2. if wrong, the right way to do so
  3. the reason for the error message
1 Answers

The right approach is,

Attach an instance profile with lambda invoke policy to ec2 instance. Then using Aws sdk without explicitly specifying any ak/sk. The SDK could properly get temporary token from metadata.

Related