I have been struggling for three days now to execute a bash script using php. The setup is as follows:
php in local machine ---> using aws sdk for php ---> starts an ec2 instance. - This works. Post getting the ec2 instance running, I am using
exec("bash /var/www/html/pushDatToAWS.sh")
This bash file is in my local machine and it has 777 rights and is owned by user:www-data. To provide aws credentials to PHP i am using the following code:
config.php
<?php
define("KEY",'abcde');
define("SECRET:,'secret');
define("REGION",'region');
define("VERSION" ,'version');
?>
connectToAWS.php
require('config.php');
require 'vendor/autoload.php';
use Aws\Ec2\Ec2Client;
$ec2Client = new Ec2Client([
'region' => REGION,
'version' => '2016-11-15',
'credentials' => [
'key' => KEY,
'secret' => SECRET
],
]);
$action = 'START';
$instanceIds = array('i-abcde');
if ($action == 'START') {
$result = $ec2Client->startInstances(array(
'InstanceIds' => $instanceIds,
));
} else {
$result = $ec2Client->stopInstances(array(
'InstanceIds' => $instanceIds,
));
}
This code works correctly. I am able to connect to aws and initiate the instance. Upon initiating the instance, I am trying to execute the bash script which fails.
exec("bash /var/www/html/pushDatToAWS.sh >> $trainLog");
pushDatToAWS.sh
ipad='12.345.543.21'
while true; do
echo "Checking for Working directory status"
ssh -i /var/www/html/IRISONTHECLOUD_OREGON.pem ubuntu@$ipad "bash /home/ubuntu/irisbuilder/checkWorkingDir.sh $dirName"
if [ $? -eq 0 ]
then
echo 'Working directory status check complete'
break
fi
sleep 1
echo -n
done
The pem file is modified to 400 and is owned by username:www-data. However, I am getting the error:
Load key "/var/www/html/IRISONTHECLOUD_OREGON.pem": Permission denied
[email protected]: Permission denied (publickey).
I found an aws developer blog speaking about similar problem here. Going by the suggestion given by the developer, I have added the following to my pushDatToAWS.php
putenv('AWS_DEFAULT_REGION=' . REGION);
putenv('AWS_ACCESS_KEY_ID=' . KEY);
putenv('AWS_SECRET_ACCESS_KEY=' . SECRET);
before calling exec(bash ...). I have been trying various options that I lost count of, but I could not trigger the bash script using php. Can someone provide me a workable example. I even tried hard coding the key and secret on the php file, but still wasn't working beyond initiating the ec2 instance. However the entire bash script works perfectly when I manually execute it from the terminal.