2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP,Pythonでの一時的なAWS認証情報の取得

Last updated at Posted at 2019-12-30

はじめに

AWSのEC2にアクセスキーを発行するのはアンチパターン。
キーが盗まれて使われることがあるので、キーは発行しないのが一番良い。
EC2にIAMロールっていう一時的なアクセスキーを発行するのが良いパターン。

Pythonで使う

run.py
import boto3

session = boto3.session.Session(profile_name='prodaccess')
credentials = session.get_credentials()

# この値をbotoとかで自由に使って。
print(credentials.access_key)
print(credentials.secret_key)
print(credentials.token)

boto3を使った一時的なAWS認証情報の取得

PHPで使う

Laravelで使う

aws-sdk-php-laravelってライブラリがある。

aws-sdk-php-laravel
IAM Roleを使ってAWS ElasticSearch ServiceのデータをLaravelで取得する
公式 AWS SDK for PHP への一時認証情報の提供

composer require aws/aws-sdk-php
composer.json
{
    "require": {
        "aws/aws-sdk-php-laravel": "~3.0"
    }
}

公式の通りだけど

PHP SDKを直で使う

createTokenがよし何やる。

ここにもサンプルはある。

$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];
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?