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

Laravel Aws Deploy Laravel Package

pin-cnx/laravel-aws-deploy

Artisan command to deploy Laravel to AWS EC2 Auto Scaling with near zero downtime. Creates an AMI from a master instance, builds a new launch configuration, updates the ASG, spins up new instances, and can terminate old ones.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require pin-cnx/laravel-aws-deploy
    
  2. Configure AWS Credentials: Add to .env:
    EC2_KEY=your_aws_access_key
    EC2_SECRET=your_aws_secret_key
    EC2_REGION=ap-southeast-1
    
  3. Update config/services.php: Add the ec2 configuration block with your AWS profile (e.g., AnyName) and required parameters (e.g., InstanceId, AutoScalingGroupName). Example:
    'ec2' => [
        'key' => env('EC2_KEY'),
        'secret' => env('EC2_SECRET'),
        'region' => env('EC2_REGION'),
        'profiles' => [
            'AnyName' => [
                'InstanceId' => 'i-0123456789abcdef',
                'AutoScalingGroupName' => 'my-auto-scale',
                'SecurityGroups' => 'sg-123456',
                'KeyName' => 'serverkey',
                'AMI_PREFIX' => 'AWSDEPLOY',
                'InstanceType' => 't3.nano',
            ],
        ],
    ],
    
  4. Run the Command: Deploy all profiles:
    php artisan ec2backup
    
    Or deploy a specific profile:
    php artisan ec2backup --profile AnyName
    

First Use Case

Zero-Downtime Deployment: Use this package to deploy updates to an Auto Scaling Group (ASG) without interrupting service. For example:

  • Your Laravel app runs on an ASG with 2 instances.
  • Push a new code version to your master instance (InstanceId).
  • Run php artisan ec2backup to:
    1. Create an AMI from the master instance.
    2. Update the ASG’s launch configuration to use the new AMI.
    3. Terminate old instances and launch new ones with the updated AMI.
  • Traffic shifts seamlessly to the new instances.

Implementation Patterns

Workflows

1. Profile-Based Deployments

  • Define multiple profiles in config/services.php for different environments (e.g., staging, production).
  • Run deployments sequentially or selectively:
    php artisan ec2backup --profile=staging --profile=production
    
  • Use Case: Isolate deployments for testing (staging) before production.

2. Custom User Data Scripts

  • Inject first-boot commands via UserData to automate post-deployment tasks. Example:
    'UserData' => "#!/bin/bash\n" .
                 "cd /var/www/html && git pull origin main && " .
                 "composer install --no-dev --optimize-autoloader && " .
                 "php artisan config:cache && php artisan cache:clear",
    
  • Use Case: Ensure new instances are pre-configured (e.g., pull latest code, cache configs).

3. Tagging New Instances

  • Add metadata to new instances via AMI_TAGS for tracking or cost allocation. Example:
    'AMI_TAGS' => [
        ['Key' => 'Environment', 'Value' => 'Production'],
        ['Key' => 'Owner', 'Value' => 'DevOps'],
    ],
    
  • Use Case: Integrate with AWS Cost Explorer or IAM policies.

4. Multi-AZ Deployments

  • Specify multiple subnets (region) to distribute instances across Availability Zones (AZs). Example:
    'region' => ['ap-southeast-1a', 'ap-southeast-1b'],
    
  • Use Case: Improve fault tolerance by spanning AZs.

5. Conditional Termination

  • Disable instance termination (IsTerminateCurrentInstance) for blue-green deployments. Example:
    'IsTerminateCurrentInstance' => false,
    
  • Use Case: Keep old instances running alongside new ones for rollback testing.

Integration Tips

Laravel Artisan Scheduling

  • Automate deployments during low-traffic periods using Laravel’s task scheduling:
    // app/Console/Kernel.php
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('ec2backup --profile=production')
                 ->dailyAt('3:00'); // 3 AM UTC
    }
    
  • Tip: Combine with before/after hooks to run pre/post-deployment tasks (e.g., database migrations).

Environment-Specific Configs

  • Use Laravel’s environment files (e.g., .env.staging, .env.production) to override AWS credentials and profiles. Example .env.production:
    EC2_KEY=prod_aws_key
    EC2_SECRET=prod_aws_secret
    

Logging and Monitoring

  • Wrap the command in a service class to log AWS API responses or errors:
    use PinCnx\LaravelAwsDeploy\Deployer;
    
    class AwsDeployService {
        public function deploy(string $profile)
        {
            try {
                $deployer = new Deployer(config('services.ec2.profiles.'.$profile));
                $deployer->deploy();
                Log::info("Deployment successful for profile: {$profile}");
            } catch (\Exception $e) {
                Log::error("Deployment failed: {$e->getMessage()}");
                throw $e;
            }
        }
    }
    
  • Tip: Integrate with Laravel Horizon or external monitoring (e.g., Datadog) for alerts.

CI/CD Pipeline

  • Trigger deployments from GitHub Actions, GitLab CI, or Jenkins:
    # .github/workflows/deploy.yml
    jobs:
      deploy:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v2
          - uses: actions/setup-php@v2
          - run: composer install
          - run: php artisan ec2backup --profile=production
            env:
              EC2_KEY: ${{ secrets.AWS_ACCESS_KEY_ID }}
              EC2_SECRET: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
    

Gotchas and Tips

Pitfalls

1. AWS Credentials Permissions

  • Issue: 401 Unauthorized errors if IAM roles lack permissions for ec2:DescribeInstances, ec2:CreateImage, or autoscaling:UpdateAutoScalingGroup.
  • Fix: Attach the AmazonEC2FullAccess and AmazonAutoScalingFullAccess policies to the IAM user/role.
  • Tip: Use least-privilege policies (e.g., restrict to specific regions or instance actions).

2. Instance State Dependencies

  • Issue: The master instance must be in a running state; otherwise, AMI creation fails.
  • Fix: Add a pre-deployment check:
    $instance = $ec2->describeInstances(['InstanceIds' => [$instanceId]]);
    if ($instance['Instances'][0]['State']['Name'] !== 'running') {
        throw new \RuntimeException("Master instance must be running.");
    }
    

3. Security Group Mismatches

  • Issue: New instances may fail to launch if the SecurityGroups ID is invalid or lacks required rules (e.g., SSH, HTTP).
  • Fix: Validate the security group exists and has the correct rules:
    aws ec2 describe-security-groups --group-ids sg-123456
    

4. AMI Naming Conflicts

  • Issue: Duplicate AMI names (e.g., AWSDEPLOY-2023-01-01) if deployments run frequently.
  • Fix: Append a timestamp or hash to the AMI_PREFIX:
    'AMI_PREFIX' => 'AWSDEPLOY-'.now()->format('YmdHis'),
    

5. User Data Script Failures

  • Issue: Silent failures in UserData scripts (e.g., missing dependencies) may leave instances in a broken state.
  • Fix: Add error handling and logging to the script:
    #!/bin/bash
    set -e  # Exit on error
    echo "Starting deployment..." >> /var/log/user-data.log 2>&1
    # Your commands here
    

6. Auto Scaling Group Health Checks

  • Issue: New instances may be terminated if they fail health checks (e.g., /health endpoint returns 500).
  • Fix: Test health checks locally before deployment and monitor ASG events in AWS Console.

Debugging

1. Enable AWS SDK Debugging

Add this to config/services.php to log AWS API calls:

'ec2' => [
    'debug' => true, // Enable AWS SDK debugging
    // ... other config
],
  • Output: Debug logs appear in `
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony