Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehains/375b85ca8da5a9a8e54e96b838ecd1eb to your computer and use it in GitHub Desktop.
Save mikehains/375b85ca8da5a9a8e54e96b838ecd1eb to your computer and use it in GitHub Desktop.
<?php
/* ----------------------------------------------------------------------------
Create a file in root directory, called: composer.json
with the following content:
{
"require": {
"aws/aws-sdk-php": "*"
}
}
---------------------------------------------------------------------------- */
require 'vendor/autoload.php';
use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
//Create a Secrets Manager Client
$client = new SecretsManagerClient([
/* ---------------------------------------------
NOTE: Credentials come from IAM ... being given to a specific EC2
role ... that is the role of the machine running this code
--------------------------------------------- */
'version' => '2017-10-17',
'region' => 'ap-southeast-1'
]);
$secretName = 'xxaaabbb';
//$description = "Token for ajax calls";
//$secret = random_bytes(32);
try {
$time1 = microtime(true);
$result = $client->getSecretValue([
'SecretId' => $secretName,
]);
$time2 = microtime(true);
echo 'script execution time: ' . ($time2 - $time1) . PHP_EOL; //value in seconds
} catch (AwsException $e) {
$error = $e->getAwsErrorCode();
if ($error == 'DecryptionFailureException') {
// Secrets Manager can't decrypt the protected secret text using the provided AWS KMS key.
// Handle the exception here, and/or rethrow as needed.
throw $e;
}
if ($error == 'InternalServiceErrorException') {
// An error occurred on the server side.
// Handle the exception here, and/or rethrow as needed.
throw $e;
}
if ($error == 'InvalidParameterException') {
// You provided an invalid value for a parameter.
// Handle the exception here, and/or rethrow as needed.
throw $e;
}
if ($error == 'InvalidRequestException') {
// You provided a parameter value that is not valid for the current state of the resource.
// Handle the exception here, and/or rethrow as needed.
throw $e;
}
if ($error == 'ResourceNotFoundException') {
// We can't find the resource that you asked for.
// Handle the exception here, and/or rethrow as needed.
throw $e;
}
}
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if (isset($result['SecretString'])) {
$secret = $result['SecretString'];
echo $secret;
} else {
echo "RESULT IS BINARY";
$secret = $result['SecretBinary'];
echo bin2hex($secret) . PHP_EOL;
echo "---------------------------";
echo "length is: " . strlen($secret);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment