2
5

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 5 years have passed since last update.

AWS SDK for PHP で ~/.aws/config に書かれた profile を使うときの注意点

Posted at

TL:DR

詳細

以下のように、AWSの認証設定がしてあるとします。

~/.aws/config
[profile project1]
role_arn = arn:aws:iam::123456789012:role/testing
source_profile = default
role_session_name = OPTIONAL_SESSION_NAME
~/.aws/credentials
[project2]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY

で、AWS SDK for PHPを使ったプログラムを実行すると、以下のコードあたりでエラーになります。

vendor/aws/aws-sdk-php/src/AwsClientTrait.php

    public function execute(CommandInterface $command)
    {
        return $this->executeAsync($command)->wait();
    }

私の場合は、PHPUnitで動作確認していたのですが、コンソールに出力されるメッセージが、接続に失敗したことだけわかるような感じだったので、この解決策にたどり着くのに相当時間がかかってしまいました。

$ AWS_PROFILE=project1 vendor/bin/phpunit

1) App\Tests\ExampleTest::testMethod
GuzzleHttp\Exception\ConnectException: cURL error 28:  (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)

ちなみに、私は前述のドキュメントではなく、下記のソースコードからAWS_SDK_LOAD_NONDEFAULT_CONFIGが必要なことを知りました。

vendor/aws/aws-sdk-php/src/Credentials/CredentialProvider.php
    private static function loadProfiles($filename)
    {
        $profileData = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);

        // If loading .aws/credentials, also load .aws/config when AWS_SDK_LOAD_NONDEFAULT_CONFIG is set
        if ($filename === self::getHomeDir() . '/.aws/credentials'
            && getenv('AWS_SDK_LOAD_NONDEFAULT_CONFIG')
        ) {
            $configFilename = self::getHomeDir() . '/.aws/config';
            $configProfileData = \Aws\parse_ini_file($configFilename, true, INI_SCANNER_RAW);
            foreach ($configProfileData as $name => $profile) {
                // standardize config profile names
                $name = str_replace('profile ', '', $name);
                if (!isset($profileData[$name])) {
                    $profileData[$name] = $profile;
                }
            }
        }

        return $profileData;
    }
$ AWS_PROFILE=project1 AWS_SDK_LOAD_NONDEFAULT_CONFIG=1 vendor/bin/phpunit
PHPUnit 7.5.16 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.2.19
Configuration: /path/to/app/phpunit.xml

...                                                                 3 / 3 (100%)

Time: 4.01 seconds, Memory: 18.00 MB

OK (3 tests, 3 assertions)

補足

冒頭にも書きましたが、この記事は、aws/aws-sdk-phpv3.102.0以降の話です。
それ以前は、前述のCredentialProvider::loadProfiles関数ごと存在しないです。

2
5
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
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?