Lambda(PHP)からSecrets Managerにアクセスする方法

Lambda(PHP)からSecrets Managerにアクセスする方法

前提

項目 バージョン
OS Ubuntu 20.04.4 LTS
PHP PHP 7.4.3-4ubuntu2.17 (cli) (built: Jan 10 2023 15:37:44) ( NTS )

Composerインストール済みであること

$ sudo apt update
$ sudo apt install -y php-curl
$ sudo apt install -y php7.4-xml
$ sudo apt install -y composer

aws sdkインストール

composerでaws sdkをインストールします。

$ composer require bref/bref
$ vendor/bin/bref init
 What kind of lambda do you want to create? (you will be able to add more functions later by editing `serverless.yml`) [Web application]:
  [0] Web application
  [1] Event-driven function
 > 1
$ composer require aws/aws-sdk-php

index.php

index.phpを修正します。

<?php
require __DIR__ . '/vendor/autoload.php';

use Aws\SecretsManager\SecretsManagerClient; 
use Aws\Exception\AwsException;

return function ($event) {
    $client = new SecretsManagerClient([
        'version' => '2017-10-17',
        'region' => 'ap-northeast-1',
    ]);
    try {
        $result = $client->getSecretValue([
        'SecretId' => 'xxx' // シークレット名
        ]);
    } catch (AwsException $e) {
        $error = $e->getAwsErrorCode();
        var_dump($error);
        exit(500);
    }
    $secret = json_decode($result['SecretString'],true);
    var_dump($secret); // ログ出力
    return "ok";
};

デプロイします。

$ sls deploy

Lambda実行すると、ログに出力されます。

参考サイト

Installation — AWS SDK for PHP documentation
Managing secrets using the Secrets Manager API and the Amazon SDK for PHP Version 3 - Amazon SDK for PHP
Amazon Secrets Manager code examples for the Amazon SDK for PHP Version 3.

コメント

タイトルとURLをコピーしました