I have written this standalone program in PHP for EC2 Instance to read secrets from SecretsManager (EC2 Instance and Secret are in the same region). I have AWS SDK PHAR in the same folder as the program below.
<?php
require 'aws.phar'; // Include the AWS SDK for PHP
use Aws\SecretsManager\SecretsManagerClient;
use Aws\Sts\StsClient;
use Aws\Exception\AwsException;
$client = new SecretsManagerClient([
'version' => 'latest',
'region' => 'us-west-1',
]);
$result = $client->getSecretValue([
'SecretId' => 'prod/vserver/api-keys',
]);
$secretString = $result['SecretString'];
I want the EC2 Instance to retrieve the secret without providing any explicit AWS credentials. I have created a IAM Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadSecrets",
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:us-west-1:ACCOUNTID:secret:prod/vserver/api-keys"
}
]
}
I have created a ROLE : EC2_ACCESS_SECRETSMANAGER and attached the Policy to the Role and the IAM Role to the EC2 Instance from where I am running the PHP Program.
But I am getting error:
Next Aws\SecretsManager\Exception\SecretsManagerException: Error executing "GetSecretValue" on "https://secretsmanager.us-west-1.amazonaws.com"; AWS HTTP error: Client error: POST https://secretsmanager.us-west-1.amazonaws.com resulted in a 400 Bad Request response:
{"__type":"AccessDeniedException","Message":"User: arn:aws:sts::<AWS_ACCOUNT_ID>:assumed-role/EC2_ACCESS_SECRETSMANAGER/i-08 (truncated...)
AccessDeniedException (client): User: arn:aws:sts::<AWS_ACCOUNT_ID>:assumed-role/EC2_ACCESS_SECRETSMANAGER/ is not authorized to perform: secretsmanager:GetSecretValue on resource: prod/vserver/api-keys because no identity-based policy allows the secretsmanager:GetSecretValue action - {"__type":"AccessDeniedException","Message":"User: arn:aws:sts::<AWS_ACCOUNT_ID>:assumed-role/EC2_ACCESS_SECRETSMANAGER/ is not authorized to perform: secretsmanager:GetSecretValue on resource: prod/vserver/api-keys because no identity-based policy allows the secretsmanager:GetSecretValue action"} in phar:///var/www/html/aws.phar/Aws/WrappedHttpHandler.php:195
, <AWS_ACCOUNT_ID> are replaced placeholder values for posting here.