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

Secrets Loader Laravel Package

bref/secrets-loader

Load AWS SSM Parameter Store secrets into environment variables at runtime when using Bref on AWS Lambda. Any env var value starting with bref-ssm: is automatically replaced with the corresponding SSM parameter value. Install via composer require bref/secrets-loader.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:
    composer require bref/secrets-loader
    
  2. Update serverless.yml: Add bref-ssm: prefixed environment variables under provider.environment:
    provider:
        environment:
            DB_PASSWORD: bref-ssm:/my-app/db-password
            API_KEY: bref-ssm:/my-app/api-key
    
  3. Deploy: Run bref deploy to push changes to AWS Lambda. The package automatically replaces bref-ssm: placeholders with SSM values at runtime.

First Use Case

Replace hardcoded Laravel .env secrets (e.g., DB_PASSWORD) with SSM-backed values in serverless.yml. Verify by checking Lambda’s environment variables in AWS Console > Lambda > Configuration > Environment variables or via CloudWatch logs:

// In a Laravel route or command
dd(env('DB_PASSWORD')); // Should show the SSM value

Where to Look First

  • Bref Secrets Documentation for syntax and examples.
  • serverless.yml to define bref-ssm: variables.
  • AWS SSM Parameter Store to create and manage parameters (ensure IAM permissions are set).

Implementation Patterns

Usage Patterns

1. Laravel Configuration Integration

  • Pattern: Use bref-ssm: in serverless.yml for secrets that Laravel reads via env() or config().
  • Example:
    # serverless.yml
    environment:
        APP_KEY: bref-ssm:/laravel/app-key
        DB_CONNECTION: bref-ssm:/laravel/db-connection
    
    // Laravel config/database.php
    'password' => env('DB_PASSWORD'), // Resolved from SSM
    
  • Tip: Clear Laravel’s config cache post-deployment if using config:cache:
    php artisan config:clear
    

2. Multi-Environment Secrets

  • Pattern: Use SSM parameter paths with environment prefixes (e.g., /dev/, /prod/).
  • Example:
    # serverless.yml (dev)
    environment:
        API_URL: bref-ssm:/my-app/dev/api-url
    
    # serverless.yml (prod)
    environment:
        API_URL: bref-ssm:/my-app/prod/api-url
    
  • Tooling: Manage parameters via AWS Systems Manager or Terraform:
    # Terraform example
    resource "aws_ssm_parameter" "api_url_prod" {
      name  = "/my-app/prod/api-url"
      type  = "SecureString"
      value = "https://prod.example.com"
    }
    

3. Fallback Values

  • Pattern: Provide default values in serverless.yml for development/local testing.
  • Example:
    environment:
        DB_PASSWORD: ${env:DB_PASSWORD, 'bref-ssm:/my-app/db-password'}
    
  • Local Workaround: Use a placeholder script (e.g., env-substituter.php) to replace bref-ssm: with .env values during local development.

4. Async SSM Fetching

  • Pattern: Leverage async-aws/ssm v2.x for non-blocking SSM calls (reduces cold-start latency).
  • Configuration: Ensure your composer.json or serverless.yml uses the latest async-aws/ssm:
    composer require async-aws/ssm:^2.0
    
  • Bref Integration: The package auto-detects async mode; no additional setup is required.

5. Dynamic Secrets with Feature Flags

  • Pattern: Store feature flags or dynamic configs in SSM and toggle them without redeploying.
  • Example:
    environment:
        FEATURE_NEW_CHECKOUT: bref-ssm:/my-app/features/new-checkout
    
    if (env('FEATURE_NEW_CHECKOUT') === 'enabled') {
        // Enable new feature
    }
    

Workflows

CI/CD Pipeline Integration

  1. GitHub Actions Example:
    - name: Deploy to AWS Lambda
      run: |
        bref deploy --set-env=API_KEY=bref-ssm:/my-app/api-key
    
  2. Terraform + Bref:
    • Use Terraform to provision SSM parameters and IAM roles, then deploy Bref via bref deploy.

Secrets Rotation

  1. AWS Native Rotation:
    • Use AWS Secrets Manager to rotate secrets and replicate them to SSM.
    • Example: Rotate DB_PASSWORD via Secrets Manager, then update the SSM parameter.
  2. Manual Rotation:
    • Update SSM parameters via AWS Console or CLI:
      aws ssm put-parameter --name /my-app/db-password --value "new_password" --type SecureString
      
    • No Lambda Restart Needed: Changes to SSM parameters are picked up on subsequent Lambda invocations.

Integration Tips

Laravel-Specific Tips

  • Environment Variable Overrides:
    • Use Bref\SecretsLoader\SecretsLoader::load() in a Lambda bootstrap file (e.g., bootstrap/app.php) to force-reload secrets:
      require __DIR__.'/../../vendor/autoload.php';
      (new \Bref\SecretsLoader\SecretsLoader())->load();
      $app = require __DIR__.'/../bootstrap/app.php';
      
  • Testing:
    • Mock SSM responses in Laravel tests using AWS SDK stubs:
      use Aws\Ssm\SsmClient;
      $ssm = Mockery::mock(SsmClient::class);
      $ssm->shouldReceive('getParameter')->andReturn(['Parameter' => ['Value' => 'mocked_value']]);
      

AWS IAM Best Practices

  • Least Privilege: Restrict SSM access to specific parameters:
    {
      "Effect": "Allow",
      "Action": "ssm:GetParameter",
      "Resource": [
        "arn:aws:ssm:REGION:ACCOUNT_ID:parameter/my-app/*",
        "arn:aws:ssm:REGION:ACCOUNT_ID:parameter/shared/*"
      ]
    }
    
  • Parameter Policies: Use SSM Parameter Store policies to enforce encryption (e.g., KMS).

Performance Optimization

  • Provisioned Concurrency: Reduce cold-start latency by keeping Lambda warm:
    # serverless.yml
    functions:
        myFunction:
            provisionedConcurrency: 5
    
  • Caching Layer: Cache SSM responses in ElastiCache (Redis) for shared secrets across Lambdas:
    $cacheKey = 'ssm_my-app_db-password';
    $value = cache($cacheKey) ?: \Bref\SecretsLoader\SecretsLoader::get('bref-ssm:/my-app/db-password');
    cache()->put($cacheKey, $value, now()->addHours(1));
    

Gotchas and Tips

Pitfalls

1. IAM Permission Errors

  • Symptom: Lambda fails with AccessDenied or ParameterNotFound.
  • Debugging:
    • Check CloudWatch logs for SecretsLoader errors.
    • Verify IAM role has ssm:GetParameter for the SSM path.
    • Test SSM access manually:
      aws ssm get-parameter --name /my-app/db-password --region REGION
      
  • Fix: Attach the correct IAM policy to the Lambda execution role.

2. Cold Start Latency

  • Symptom: Slow initial response due to SSM API calls.
  • Mitigation:
    • Use Provisioned Concurrency (as above).
    • Pre-fetch secrets in a Lambda bootstrap script:
      // bootstrap/app.php
      $loader = new \Bref\SecretsLoader\SecretsLoader();
      $loader->load(); // Blocks until secrets are loaded (avoids cold-start delay)
      

3. Laravel Config Cache Stale Values

  • Symptom: php artisan config:cache caches old SSM values.
  • Fix: Clear cache post-deployment or avoid caching secrets:
    php artisan config:clear
    
  • Alternative: Use env() directly instead of cached configs.

4. Plaintext vs. SecureString Parameters

  • Gotcha: SSM SecureString parameters are encrypted but require KMS permissions.
  • Workaround: Decrypt in Lambda using KMS:
    use Aws\Kms\KmsClient;
    $kms = new KmsClient([...]);
    $decrypted = $kms->dec
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours