我已经阅读了很多有关如何正确使用 SecretsManager 和 AWS Credentials 通过附加实例角色和 /.aws/credentials 中包含我的 AWS 凭证的配置文件来访问我的机密的内容。但现在我陷入了如何使用启动模板启动新实例时执行所有这些操作的问题。我希望在实例启动时执行所有操作,因此我希望能够在实例启动时使用有权访问 SecretsManager 的 IAM 角色检索我的机密。我以为我会在“用户数据”区域中执行此操作。但是,要获取 /.aws/credentials 文件,当 CLI 提示我使用命令“aws configure”时,我需要手动插入该数据。
我该如何自动完成这一切?顺便说一句,我根本不确定我这样做是否正确,因为我尝试在 stackoverflow 上积累大量不同的教程、AWS 文档和发现。
我正在尝试从 PHP 中的 SecretsManager 获取秘密,这是我正在尝试使用的功能,现在遇到“找不到 ~/.aws/credentials”,因为我的启动模板没有创建它靠它自己
$client = new SecretsManagerClient([
'profile' => 'default',
'version' => '2017-10-17',
'region' => 'eu-central-1',
]);
try {
$result = $client->getSecretValue([
'SecretId' => $secret_name,
]);
} 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'];
} else {
$secret = base64_decode($result['SecretBinary']);
}
return json_decode($secret, true);
}
在这里找到答案。从字面上看,它比 AWS SDK 文档本身更好地解释了 PHP 的 AWS 开发工具包凭证如何工作。
但是,通常您会希望 SDK 自动找到您的凭据。 AWS 开发工具包将按以下顺序搜索您的凭证(并非包括所有情况):
- 环境变量(AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY, 等)
- 在 ~/.aws/credentials 的默认配置文件部分
- EC2 IAM 角色
一般就用这个例子,让SDK找到 给您的凭证:
use Aws\Credentials\CredentialProvider; use Aws\S3\S3Client; // Use the default credential provider $provider = CredentialProvider::defaultProvider(); // Pass the provider to the client $client = new S3Client([ 'region' => 'us-west-2', 'version' => '2006-03-01', 'credentials' => $provider ]);
https://stackoverflow.com/a/51525021/4080920
基本上,我使用附加到我的 EC2 实例的 IAM 角色,并使用:
CredentialProvider::defaultProvider();
否则上面的原始答案就是事实。
https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_provider.html