Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Spiral's avatar

environment variable values are not being used in the database connection

I am facing an issue with my Laravel application deployment on AWS ECS. The deployment process involves Jenkins, AWS ECR, and ECS. The new task is created, but there's an "Access Denied" error connecting to the RDS database.

I have provided my deployment files for reference.

pipeline {

    agent any

    environment {
        AWS_ACCOUNT_ID="794664785634"
        AWS_DEFAULT_REGION="us-east-1"
        IMAGE_REPO_NAME="product-mangement"
        IMAGE_TAG="${BUILD_NUMBER}"
        REPOSITORY_URI = "794664785634.dkr.ecr.us-east-1.amazonaws.com/product-mangement"
        ECS_CLUSTER = "product-mangement"
        ECS_SERVICE = "product-mangement"
    }

    stages {
        stage('Checkout Latest Source') {
            steps {
                git branch: 'master',
                url: 'https://github.com/jhon-123/product-mangement',
                credentialsId: 'jenkins_pta'
            }
        }
        stage('Logging into AWS ECR') {
            steps {
                script {
                    sh """aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | docker login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com"""
                }
                 
            }
        }
        
        // Building Docker images
        stage('Building image') {
            steps{
                script {
                    dockerImage = docker.build "${IMAGE_REPO_NAME}:${IMAGE_TAG}"
                }
            }
        }
   
        // Uploading Docker images into AWS ECR
        stage('Pushing to ECR') {
            steps{  
                script {
                    sh """docker tag ${IMAGE_REPO_NAME}:${IMAGE_TAG} ${REPOSITORY_URI}:$IMAGE_TAG"""
                    sh """docker push ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${IMAGE_REPO_NAME}:${IMAGE_TAG}"""
                }
            }
        }

        stage('Deploy to ECS') {
            steps {
                sh "aws ecs update-service --cluster ${ECS_CLUSTER} --service ${ECS_SERVICE} --force-new-deployment"
            }
        }
    }
}

Dockerfile:

# Use the official PHP image as a base
FROM php:8.1-fpm

ENV COMPOSER_ALLOW_SUPERUSER 1

# Arguments defined in docker-compose.yml
ARG user
ARG uid

USER root

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    curl \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Get latest Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Create system user to run Composer and Artisan Commands
# RUN useradd -G www-data,root -u $uid -d /home/$user $user
# RUN mkdir -p /home/$user/.composer && \
  # chown -R $user:$user /home/$user

# Set the working directory
WORKDIR /var/www

# Copy the project files into the container
COPY . /var/www

# Copy .env.example to .env
COPY .env.prod .env

# Install Composer dependencies
RUN composer install

# Cache configuration
RUN php artisan config:clear
RUN php artisan config:cache

# Generate Laravel application key
RUN php artisan key:generate

# Copy the start script into the container
COPY script.sh /var/www/script.sh

# Make the script executable
RUN chmod +x /var/www/script.sh

# Expose port 8000
EXPOSE 8000

# show message
RUN echo "ehllo"

# Run the start script as the CMD
CMD ["/var/www/script.sh"]

script.sh:

#!/bin/sh

# Run Laravel migrations
php artisan config:cache
php artisan migrate

# Seed Database
php artisan db:seed
echo "seeded successfully"

# Start the Laravel application
php artisan serve --host=0.0.0.0 --port=8000

Problem: The new task is created, but there is an "Access Denied" error connecting to the RDS database. The .env.prod file contains the correct RDS connection details.

.env.prod: => I have copied the .env.prod file into .env in the Dockerfile and also I checked on the live ECS Task it is there but ECS is not getting credentials from the secret manager. I'm very confused

.env.prod

APP_NAME=Laravel
APP_ENV=prod
APP_KEY=base64:LyxaydSCa8HIgUdaLLQCPehtSK2siVr0o+bT6jcXWmM=
APP_DEBUG=false
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=product-management.c7ebhtqyydqk.us-east-1.rds.amazonaws.com
DB_PORT=3306
DB_DATABASE=product-management
#DB_USERNAME=laravel
#DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Question: What could be causing the "Access Denied" error in the deployment process, and how can I resolve it? Any insights or suggestions for troubleshooting would be greatly appreciated.

i have RDS connection through Secret Manager and in Task Definition I have added these permissions as a Task Role within the Role

AmazonEC2ContainerServiceRole
AmazonECS_FullAccess
AmazonECSTaskExecutionRolePolicy
AmazonRDSDataFullAccess
AmazonRDSFullAccess

Secret Manager credential that i have added in ECS Task Definition

arn:aws:secretsmanager:us-east-1:794664117291:secret:product-management-secrets-83qahw::username:
arn:aws:secretsmanager:us-east-1:794664117291:secret:product-management-secrets-83qahw::password:

and Engine, Host, and Port I have added in .env.example file that I'm copying into Dockerfile.

I have also checked with SSH into ECS Task and did check that the .env.example is copying into .env but the issue is that ECS is not getting the secret manager environment variable and due to that coming Access Denied issue and ECS getting default database forge from config/database.php

I also check if those environment variables are actually present inside the ECS container, and that they have the correct values.

Yes, Environment variables are present in the ECS Container, and these values. can you please check the picture that I have attached Environment Variables inside ECS container

SSH into the task, and run echo $DB_PASSWORD and echo $DB_USERNAME i did ssh and run echo $DB_PASSWORD and echo $DB_USERNAME values are coming Secret Manager values in Container

I have tried a lot but didn't get any solution I have added logs in my Laravel application and I have checked on Service Created Task IP then got this in logs Laravel logs screenshot and also got the same issue in Task logs.

0 likes
1 reply

Please or to participate in this conversation.