How to invoke an existing AWS Lambda function from laravel? - php

I am trying to invoke an existing aws-lambda function from my php code in laravel to get the data and save in my database.
The actual command I want to invoke is the following:
aws lambda invoke --function-name expo2020-metrics --region eu-west-3 response.json
Here is the code I'm using to invoke my function:
use Aws\Lambda\LambdaClient;use Aws\Credentials\Credentials;
$credentials = new Credentials('YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY');
$client = LambdaClient::factory(array(
'credentials' => $credentials,
'region' => 'eu-west-3',
'version' => 'latest'
));
$result = $client->getFunction(array(
'FunctionName' => 'expo2020-metrics',
));
But I'm getting the following response:
{"Message":"User: arn:aws:iam::677537359471:user/customer/expo2020-metrics is not authorized to perform: lambda: GetFunction on resource: arn:aws:lambda:eu-west-3:677537359471:function:expo2020-metrics"}
I'm not sure that I'm using the right code to invoke the function or not. I am using the PHP sdk provided by AWS.

You are calling getFunction which just gives you information about the Lambda function. That is not equivalent to the aws lambda invoke CLI command you are trying to translate into PHP.
You should be calling the invoke() function of the Lambda client.

Here is a sample code on Gist: https://gist.github.com/robinvdvleuten/e7259939267ad3eb1dfdc20a344cc94a.
require_once __DIR__.'/vendor/autoload.php';
use Aws\Lambda\LambdaClient;
$client = LambdaClient::factory([
'version' => 'latest',
'region' => 'eu-west-1',
'credentials' => [
'key' => 'YOUR_AWS_ACCESS_KEY_ID',
'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
]
]);
$result = $client->invoke([
'FunctionName' => 'hello-world',
]);
var_dump($result->get('Payload'));

Related

how to get statuscode from aws s3 putobject response

I am sending file to AWS s3 using PHP SDK. I installed SDK using
composer require aws/aws-sdk-php
I am using following code
require_once('vendor/autoload.php');
$s3 = new Aws\S3\S3Client([
'region' => AWS_REGION,
'version' => 'latest',
'credentials' => [
'key' => AWS_ACCESS_KEY_ID,
'secret' => AWS_SECRET_ACCESS_KEY,
]
]);
$result = $s3->putObject([
'Bucket' => AWS_BUCKET,
'Key' => $filename,
'SourceFile' => $fileFullPath
]);
Following response, I am getting
I am trying to get status code from this response and tried different ways, but I could not get status code.
You are returned an object with a private array called "data" but you are also able to just call the data by attribute. So using $result['#metadata']['statusCode'] works just fine.
$result['#metadata']['statusCode'] == 200
According to your example.
Worked fine for me
$result['#metadata']['statusCode'] == 200

Credentials must be an instance of Aws\\Credentials\\CredentialsInterface error on PHP SDK with SQS

I am trying to delete a message from SQS in AWS using the php SDK. I have the following configuration.
$sqsClient = new SqsClient([
'version' => '2012-11-05',
'region' => 'us-east-1',
'credentials' => [
'key' => KEY,
'secret' => SECRET
]
]);
Then I am trying to delete like the following :
$sqsClient->deleteMessage([
'QueueUrl' => quque-url
'ReceiptHandle' => handle
]);
I am getting the following error on initialization :
Credentials must be an instance of Aws\\Credentials\\CredentialsInterface, an associative array that contains \"key\", \"secret\", and an optional \"token\" key-value pairs, a credentials provider function, or false."
The credentials I am using is correct. Before I was not passing the config and then also the same error was appearing. How this can be fixed ?
I found this code example and I think your code is correct.
How about create instance of Credentials?
You can use these code for initiating instance.
$credentials = new Aws\Credentials\Credentials(KEY, SECRET);
$sqsClient = new SqsClient([
'version' => '2012-11-05',
'region' => 'us-east-1',
'credentials' => $credentials
]);
Check this document.
And for security reason, I recommend that you'd better use credentials file or set environment variable.
I hope all is well.

AWS SDK PHP - Cannot read credentials from /.aws/credentials

There seems to be an error either in the documentation or the SDK itself.
The SDK keeps looking for the standard credentials file while there is none.
require('aws/aws-autoloader.php');
use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;
$profile = 'default';
$inipath = '/www/test/.test/credentials.ini';
$provider = CredentialProvider::ini($profile, $inipath);
$provider = CredentialProvider::memoize($provider);
use Aws\Exception\AwsException;
try {
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'eu-central-1',
'version' => '2006-03-01',
'credentials' => $provider,
]);
It fails with this error:
Uncaught Aws\Exception\CredentialsException: Cannot read credentials from /.aws/credentials in /www/test/aws/Aws/Credentials/CredentialProvider.php:394
Does anybody have a clue on how fix this?
I removed 'profile' => 'default', from the s3client and it worked.
It seemed the profiles were defined twice.

How to get aws service with aws-sfk-php-zf2 v 2.0.*?

I was using aws/aws-sdk-php-zf2 1.2.* and had to upgrade to 2.0.* and the AWS SDK is v3 now.
Before I called it using the code:
$this->s3 = $serviceLocator->get('aws')->get('s3');
But now its returning this error:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for aws
Couldn't find the difference in the migration documentation.
Any tips?
Instead of fetching the service by the key: Aws you should now use the FQCN of the SDK class.
use Aws\Sdk as Aws;
$aws = $serviceLocator->get(Aws::class);
See the module.config.php of the aws/aws-sdk-php-zf2 module.
I found an way that worked for me.
It's like that now:
use Aws\S3\S3Client;
$this->s3 = S3Client::factory(array(
'credentials' => array(
'key' => $this->config['aws']['key'],
'secret' => $this->config['aws']['secret'],
),
'region' => $this->config['aws']['region'],
'version' => '2006-03-01'
));

Amazon SNS to push topic using PHP

I'm trying to understand amazon php sdk for AWS but I really can't use it.
I find some basic classes to create, display and push topic but I doesn't work either.
I just want to find a way (the simplest way) to push a topic from my website.
First and foremost, to get acquainted with Amazon Simple Notification Service (SNS), I recommend to perform all required step manually once via the AWS Management Console as explained in the Getting Started Guide, i.e. Create a Topic, Subscribe to this Topic and Publish a message to it.
Afterwards it should be fairly straight forward to facilitate the sample fragments provided in the documentation of the AWS SDK for PHP running, see e.g. method publish() within class AmazonSNS:
$sns = new AmazonSNS();
// Get topic attributes
$response = $sns->publish(
'arn:aws:sns:us-east-1:9876543210:example-topic',
'This is my very first message to the world!',
array(
'Subject' => 'Hello world!'
)
);
// Success?
var_dump($response->isOK());
For a more complete example you might want to check out the the example provided in Sending Messages Using SNS [...].
If none of this works out, you'll have to provide more details regarding the specific problems you are encountering, as requested by tster already.
Good luck!
As told to you by #SteffenOpel, you should once try to perform all required steps manually once via the AWS Management Console.
Then you may use the AWS SDK for PHP(v3) as below to create the SNS client(or infact any service's client, surely with some changes) and then to create a SNS Topic.
<?php
//assuming that use have downloaded the zip file for php sdk
require 'C:/wamp/www/aws sdk/aws-autoloader.php'; //Change the path according to you
use Aws\Sns\SnsClient;
try{
/*-------------METHOD 1----------------*/
// Create a new Amazon SNS client using AWS v3
//$sns = new Aws\Sns\SnsClient([
$sns = new SnsClient([
'region' => 'us-west-2', //Change according to you
'version' => '2010-03-31', //Change according to you
'credentials' => [
'key' => '<Your root AWS Key',
'secret' => '<Your root AWS Secret>',
],
'scheme' => 'http', //disables SSL certification, there was an error on enabling it
]);
$result = $sns -> createTopic([
'Name' => '<Your Topic>',
]);
/*-------------METHOD 2----------------*/
/*
// Create a new Amazon SNS client using AWS v2
$sns = SnsClient::factory(array(
'region' => 'us-west-2',
'version' => '2010-03-31',
'credentials' => [
'key' => '<Your root AWS Key',
'secret' => '<Your root AWS Secret>',
],
'scheme' => 'http',
));
$result = $sns -> createTopic([
'Name' => '<Your Topic>',
]);
*/
/*-------------METHOD 3----------------*/
/*
// Create a new Amazon SNS client using AWS SDK class
// Use the us-west-2 region and latest version of each client.
$sharedConfig = [
'region' => 'us-west-2',
'version' => '2010-03-31',
'credentials' => [
'key' => '<Your root AWS Key',
'secret' => '<Your root AWS Secret>',
],
//'ssl.certificate_authority' => '/path/to/updated/cacert.pem',
'scheme' => 'http',
];
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($sharedConfig);
$sns = $sdk -> createSns();
$result = $sns -> createTopic([
'Name' => '<Your Topic>',
]);
*/
if ($result)
echo "Yes";
else
echo "No";
}
catch(Exception $e){
echo 'Caught Exception: ', $e->getMessage(), "\n";
}
?>
NOTE: This code illustrates creating the client for SNS in three different methods.
You may uncomment and use one according to your need.
Method 1 (version 3) is the best if you're creating a single client, else use Method 3. Method 2 is soon gonna depreciate (as its version 2)
I success to do it by using this classes->
Amazon-SNS-client-for-PHP
Very good, easy to use and working just great.
According to the AWS official docs here, we will have to create a SnsClient and call it's publish method. You can get topic's ARN from AWS console.
$SnSclient = new SnsClient([
'profile' => 'default',
'region' => 'us-east-1',
'version' => '2010-03-31'
]);
$message = 'This message is sent from a Amazon SNS code sample.';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';
try {
$result = $SnSclient->publish([
'Message' => $message,
'TopicArn' => $topic,
]);
var_dump($result);
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
}

Categories