Use AWS credentials with Symfony without hardcoding them.

Use AWS credentials with Symfony without hardcoding them.

Introduction

In this article, I will show an example how to implement AWS credentials with Symfony to avoid hardcoding credentials in codebase.

Step 1: Install the AWS SDK for PHP

terminal
composer require aws/aws-sdk-php

Step 2: Add some AWS variables to the .env file

.env
ENV_PROFILE=<profile_name> #more info https://docs.aws.amazon.com/en_us/aws-sdk-php/guide/latest/guide/credentials.html#using-iam-roles-for-amazon-ec2-instances
AMAZON_S3_REGION=<some_region> # e.g. us-east-1
AMAZON_S3_VERSION=<s3_api_version> # e.g. latest
AMAZON_S3_ENDPOINT=<s3_endpoint> # e.g. https://bucket-name.s3.amazonaws.com
.env.local
#for local dev

AMAZON_S3_KEY=<your_key>
AMAZON_S3_SECRET=<your_secret>

Step 3: Configure services

config/services.yaml
services:
    parameters:
        amazon_s3_region: '%env(AMAZON_S3_REGION)%'
        amazon_s3_version: '%env(AMAZON_S3_VERSION)%'

    aws_credentials_provider:
        class: Aws\Credentials\CredentialProvider

    aws_s3_client:
        class: Aws\S3\S3Client
        factory: [Aws\S3\S3Client, factory]
        arguments:
            -   credentials: '@aws_credentials_provider'
                region: '%amazon_s3_region%'
                version: "%amazon_s3_version%"
                endpoint: '%amazon_s3_endpoint%'


### for local dev
when@dev:
    parameters:
        amazon_s3_endpoint: '%env(AMAZON_S3_ENDPOINT)%'

    services:
        aws_s3_client:
            class: Aws\S3\S3Client
            factory: [ Aws\S3\S3Client, factory ]
            arguments:
                -   credentials:
                        key: '%amazon_s3_key%'
                        secret: '%amazon_s3_secret%'
                    region: '%amazon_s3_region%'
                    version: "%amazon_s3_version%"
                    endpoint: '%amazon_s3_endpoint%'