Thursday, August 20, 2020

AWS PHP SDK - Create an Entry in Route53 - Laravel

 Hello,

In this blog I will explain you how to you can create an entry in Route53 hosted zone using AWS PHP SDK. Solution I mentioned here is particularly for Laravel app, but you can still use it in any of the PHP project. 

This solution is pretty much useful when you want to make a dynamic entry in your hosted. For example a dynamic sub domain creation. 

First of all your need install couple of packages using composer. Following are the packages. 

"aws/aws-sdk-php": "^3.148",

"aws/aws-sdk-php-laravel": "~3.0",

You can either install it by adding it in composer.json file or you can install it using composer require. 

Once the installation is done, follow the steps mentioned in below URL. 

https://github.com/aws/aws-sdk-php-laravel

Once installation is done. You need to add following keys in your env file.

AWS_ACCESS_KEY_ID

AWS_SECRET_ACCESS_KEY

AWS_REGION (default = us-east-1)

Set the values in above keys from your AWS account. That's it your AWS SDK is ready. Now add following line your controller where you want to have logic for adding value in Route53

use Aws\Route53\Route53Client;

use Aws\Common\Credentials\Credentials;

Now next step is to create a client

$client = Route53Client::factory(array(

            'credentials' => config('aws.credentials'),

            'region' => config('aws.region'),

            'version' => config('aws.version'),

)); 

After client is created we will use changeResourceRecordSets to create an entry.

$result = $client->changeResourceRecordSets(array(

            // HostedZoneId is required

            'HostedZoneId' => 'YOUR_HOSTED_ZONE_ID',

            // ChangeBatch is required

            'ChangeBatch' => array(

                'Comment' => 'string',

                // Changes is required

                'Changes' => array(

                    array(

                        // Action is required

                        'Action' => 'CREATE',

                        // ResourceRecordSet is required

                        'ResourceRecordSet' => array(

                            // Name is required

                            'Name' => 'YOUR_VALUE',

                            // Type is required

                            'Type' => 'CNAME', //A, CANME

                            'TTL' => 600,

                            'ResourceRecords' => array(

                                array(

                                    // Value is required

                                    'Value' => 'YOUR_VALUE', //IP address or load balancer.

                                ),

                            ),

                        ),

                    ),

                ),

            ),

        ));

That's it and it will create an entry in Route53 hosted zone. 

No comments:

Post a Comment