Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Aws Secrets Bundle Laravel Package

constup/aws-secrets-bundle

Symfony bundle that loads parameters from AWS Secrets Manager into the service container. Supports Symfony 5/6 (v1/v2) and requires aws/aws-sdk-php. Configure region/credentials and reference secrets in config for environment-specific setups.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies:

    composer require aws/aws-sdk-php constup/aws-secrets-bundle:^1  # For Laravel 9.x (Symfony 5.3+)
    composer require aws/aws-sdk-php constup/aws-secrets-bundle:^2  # For Laravel 10.x+ (Symfony 6.0+)
    
  2. Configure AWS Credentials:

    • Set up AWS credentials via environment variables, IAM roles, or ~/.aws/credentials.
    • Refer to the AWS credentials guide for environment-specific setups.
  3. Add Bundle Configuration: Create or update config/packages/aws_secrets.yaml (or config/aws_secrets.php for Laravel):

    aws_secrets:
        client_config:
            region: 'us-east-1'  # Required if "ignore" is false
            version: 'latest'
        cache: 'filesystem'      # Use 'array' for local dev, 'filesystem' for staging/prod
        ignore: false            # Set to true for local development
    
  4. Define Secrets in AWS Secrets Manager:

    • Store secrets in AWS Secrets Manager (e.g., DB_PASSWORD, STRIPE_API_KEY).
    • Use JSON format for nested keys (e.g., {"username": "admin", "password": "secure123"}).
  5. Reference Secrets in Laravel: Update your .env file to reference AWS secrets:

    AWS_DB_PASSWORD=my-db-secret,password  # Format: secret_name,key (optional)
    AWS_STRIPE_KEY=stripe-api-key
    

    Bind secrets in config/services.php (or config/packages/services.yaml):

    'parameters' => [
        'db.password' => '%env(aws:AWS_DB_PASSWORD)%',
        'stripe.key' => '%env(aws:AWS_STRIPE_KEY)%',
    ],
    
  6. First Use Case: Fetch a secret dynamically in a Laravel service:

    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    
    class StripeService {
        public function __construct(private ParameterBagInterface $params) {}
    
        public function getKey() {
            return $this->params->get('stripe.key'); // Resolves to AWS secret
        }
    }
    

Implementation Patterns

Usage Patterns

  1. Environment-Specific Secrets:

    • Use different AWS Secret names per environment (e.g., dev-db-secret, prod-db-secret).
    • Override AWS_SECRET variables in .env files for each environment.
  2. Nested JSON Secrets:

    • Store complex configurations (e.g., API endpoints, feature flags) as JSON in AWS Secrets Manager.
    • Reference nested keys with a comma delimiter:
      AWS_FEATURE_FLAGS=feature-flags,enabled_features
      
    • In config/services.php:
      'feature.flags' => '%env(aws:AWS_FEATURE_FLAGS)%', // Returns JSON string
      
  3. Doctrine Database Connections: Dynamically configure Doctrine connections using AWS secrets:

    # config/packages/doctrine.yaml
    doctrine:
        dbal:
            connections:
                default:
                    url: '%env(aws:DB_URL)%'  # e.g., AWS_SECRET=db-url,url
    
  4. Queue/Service Configurations: Inject secrets into queue workers or external services:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton(SqsClient::class, function ($app) {
            return new SqsClient([
                'region' => 'us-east-1',
                'credentials' => [
                    'key' => $app['config']['aws.credentials.key'],
                    'secret' => $app['config']['aws.credentials.secret'],
                ],
                'endpoint' => $app['config']['aws.endpoint'],
            ]);
        });
    }
    
  5. Local Development Workflow:

    • Set ignore: true in config/packages/aws_secrets.yaml to bypass AWS calls locally.
    • Use .env.local to override secrets for development:
      AWS_DB_PASSWORD=local_db_password  # Overrides AWS fetch
      

Workflows

  1. Secret Rotation:

    • Update secrets in AWS Secrets Manager without redeploying.
    • Laravel will fetch the latest value on subsequent requests (cache TTL: ~1 hour by default).
  2. CI/CD Integration:

    • Inject secrets into pipelines using AWS IAM roles or temporary credentials.
    • Example GitHub Actions workflow:
      jobs:
        deploy:
          steps:
            - name: Set AWS secrets
              run: |
                echo "AWS_DB_PASSWORD=$(aws secretsmanager get-secret-value --secret-id prod-db-secret --query SecretString --output text)" >> $GITHUB_ENV
            - name: Deploy
              run: php artisan deploy
      
  3. Testing:

    • Use the array cache for local testing to avoid AWS API calls:
      aws_secrets:
          cache: 'array'
      
    • Mock AWS responses in PHPUnit:
      $this->get('aws_secrets.manager')->shouldReceive('getSecret')
          ->once()
          ->andReturn(['SecretString' => 'mocked-secret']);
      

Integration Tips

  1. Laravel-Specific Adjustments:

    • Override Symfony’s parameter bag to integrate with Laravel’s env() helper:
      // app/Providers/AppServiceProvider.php
      use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
      
      public function boot(ParameterBagInterface $params) {
          if (!function_exists('env')) {
              function env($key, $default = null) {
                  return $params->get($key) ?? $default;
              }
          }
      }
      
  2. Caching Strategies:

    • For production, use filesystem cache to reduce AWS API calls:
      aws_secrets:
          cache: 'filesystem'
          cache_dir: '%kernel.project_dir%/var/aws_secrets_cache'
      
    • Clear cache manually during deployments if secrets change frequently:
      php artisan cache:clear
      
  3. Error Handling:

    • Handle missing secrets gracefully in Laravel:
      $secret = $this->params->get('db.password');
      if (empty($secret)) {
          throw new RuntimeException('Database password not configured.');
      }
      
  4. Symfony 6.0+ Adaptations:

    • If using Laravel 10.x+, ensure HttpClient is configured to work with the bundle’s AWS SDK:
      // config/services.php
      'http_client' => [
          'base_uri' => 'https://example.com',
          'aws_sdk' => fn() => new Aws\SecretsManager\SecretsManagerClient([
              'region' => 'us-east-1',
              'version' => 'latest',
          ]),
      ],
      

Gotchas and Tips

Pitfalls

  1. AWS SDK Version Conflicts:

    • If Laravel already uses aws/aws-sdk-php, ensure the bundle uses the same version to avoid conflicts.
    • Fix: Explicitly require the same version in composer.json:
      "require": {
          "aws/aws-sdk-php": "^3.200"
      }
      
  2. Caching Issues:

    • Secrets may not update immediately if cached. Clear the cache after rotating secrets:
      php artisan cache:clear
      
    • Tip: Use a short TTL (e.g., 5 minutes) for development:
      aws_secrets:
          cache_ttl: 300  # 5 minutes
      
  3. Local Development Bypass:

    • Setting ignore: true skips AWS calls but may lead to secrets being hardcoded in .env.local.
    • Tip: Use placeholder values in .env.local and document the workflow:
      # .env.local
      AWS_DB_PASSWORD=local_override  # Only for local testing
      
  4. Symfony Version Mismatches:

    • Laravel 9.x (Symfony 5.4) may conflict with Symfony 5.3 dependencies in v1.x of the bundle.
    • Fix: Use composer why-not to identify conflicts and override dependencies:
      composer why-not symfony/dependency-injection:^5.4
      
  5. Nested JSON Parsing:

    • Secrets with nested JSON keys (e.g., secret_name,key.path) return strings. Parse manually:
      $secret = json_decode($this->params->get('aws:FEATURE_FLAGS'), true);
      
  6. IAM Permissions:

    • Ensure the IAM role/user has secretsmanager:GetSecretValue permissions for the required secrets.
    • Tip: Use IAM policies with least privilege:
      {
          "Version": "2012-10
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle