Skip to content

Instantly share code, notes, and snippets.

@sators
Last active April 11, 2024 07:17
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sators/38dbe25f655f1c783cb2c49e9873d58a to your computer and use it in GitHub Desktop.
Save sators/38dbe25f655f1c783cb2c49e9873d58a to your computer and use it in GitHub Desktop.
PHP MySQLi Amazon Aurora RDS EC2 IAM Role Based Authentication
<?php
/********* CONFIG ********/
$clusterEndpoint = "";
$clusterPort = 3306;
$clusterRegion = "us-east-1";
$dbUsername = "";
$dbDatabase = "";
/*************************/
// AWS-PHP-SDK installed via Composer
require 'vendor/autoload.php';
use Aws\Credentials\CredentialProvider;
$provider = CredentialProvider::defaultProvider();
$RdsAuthGenerator = new Aws\Rds\AuthTokenGenerator($provider);
$token = $RdsAuthGenerator->createToken($clusterEndpoint . ":" . $clusterPort, $clusterRegion, $dbUsername);
$mysqli = mysqli_init();
mysqli_options($mysqli, MYSQLI_READ_DEFAULT_FILE, "./my.cnf");
$mysqli->real_connect($clusterEndpoint, $dbUsername, $token, $dbDatabase, $clusterPort, NULL, MYSQLI_CLIENT_SSL);
if ($mysqli->connect_errno) {
echo "Error: Failed to make a MySQL connection, here is why: <br />";
echo "Errno: " . $mysqli->connect_errno . "<br />";
echo "Error: " . $mysqli->connect_error . "<br />";
exit;
}
/***** Example code to perform a query and return all tables in the DB *****/
$tableList = array();
$res = mysqli_query($mysqli,"SHOW TABLES");
while($cRow = mysqli_fetch_array($res))
{
$tableList[] = $cRow[0];
}
echo '<pre>';
print_r($tableList);
echo '</pre>';
[client]
enable-cleartext-plugin
@talhermon
Copy link

@talhermon could it be the "testuser" hardcoded in the generateRdsIamAuthToken function?

Its the name of the user, I'm using the same name when calling the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment