• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy
How to Identify RDS Reader and Writer Instances Programmatically Using AWS SDK

How to Identify RDS Reader and Writer Instances Programmatically Using AWS SDK

Arya P B

  • 3 min read
How to Identify RDS Reader and Writer Instances Programmatically Using AWS SDK

Generating audio, please wait...

Managing Amazon RDS clusters involves several critical tasks, including identifying Reader and Writer instances. This information is essential for tasks like scaling Reader instances, modifying instance types, or implementing failover mechanisms. If you’ve worked with RDS clusters, you might have noticed that identifying the role (Reader or Writer) of instances isn’t directly available in some APIs. In this blog, we’ll walk through how to programmatically determine the role of RDS instances in a cluster using the AWS SDK.

The Problem: Determining Reader and Writer Roles in RDS Clusters

RDS clusters consist of a primary Writer instance and one or more Reader instances (handling read-only queries). While the AWS Management Console conveniently labels instances as Readers or Writers, fetching this data programmatically requires additional steps.

The challenge lies in identifying roles because the describe_db_instances API doesn't directly specify whether an instance is a Reader or Writer. However, by combining data from the describe_db_clusters API, we can accurately determine roles.

The Solution

We use the WriterEndpoint attribute from the describe_db_clusters API to identify the Writer instance. The endpoint of each instance, fetched via describe_db_instances, is then compared against the WriterEndpoint to determine its role.

Here’s how you can implement this:

Step-by-Step Implementation

Below is the Python code that accomplishes the task:

import boto3

# Initialize AWS clients
rds_client = boto3.client('rds')

def list_all_rds_clusters():
clusters = []
response = rds_client.describe_db_clusters()
for cluster in response['DBClusters']:
clusters.append({
'DBClusterIdentifier': cluster['DBClusterIdentifier'],
'DBClusterArn': cluster['DBClusterArn']
})
return clusters

def list_instances_in_cluster(cluster_id):
try:
# Fetch cluster information to get WriterEndpoint
cluster_response = rds_client.describe_db_clusters(DBClusterIdentifier=cluster_id)
writer_endpoint = cluster_response['DBClusters'][0].get('WriterEndpoint')

# Fetch all DB instances and filter those in the cluster
response = rds_client.describe_db_instances()
instances = []
for instance in response['DBInstances']:
if instance.get('DBClusterIdentifier') == cluster_id:
endpoint = instance['Endpoint']['Address']
role = 'WRITER' if endpoint == writer_endpoint else 'READER'
instances.append({
'DBInstanceIdentifier': instance['DBInstanceIdentifier'],
'DBInstanceClass': instance['DBInstanceClass'],
'InstanceRole': role,
'Endpoint': endpoint
})
return instances

except Exception as e:
print(f"Error listing instances for cluster {cluster_id}: {str(e)}")
return []

def lambda_handler(event, context):
clusters = list_all_rds_clusters()
for cluster in clusters:
cluster_id = cluster['DBClusterIdentifier']
print(f"Cluster ID: {cluster_id}")
instances = list_instances_in_cluster(cluster_id)
for instance in instances:
print(f"Instance ID: {instance['DBInstanceIdentifier']}, Role: {instance['InstanceRole']}, Endpoint: {instance['Endpoint']}")

Understanding the Code

1. Fetch All RDS Clusters

The list_all_rds_clusters function retrieves all RDS clusters using describe_db_clusters.

2. Retrieve WriterEndpoint

The WriterEndpoint is extracted from the cluster’s details. This endpoint is unique to the Writer instance.

3. List Instances and Determine Roles

The list_instances_in_cluster function compares each instance’s endpoint against the WriterEndpoint. Instances with matching endpoints are labeled as Writers; others are Readers.

4. Lambda Integration

The lambda_handler function ties everything together, making it easy to deploy this logic as an AWS Lambda function.


Sample Output

When executed, the script produces the following output:

Cluster ID: prod-cluster
Instance ID: prod-cluster-instance-1, Role: READER, Endpoint: prod-cluster-instance-1.example.com
Instance ID: prod-cluster-instance-2, Role: WRITER, Endpoint: prod-cluster-instance-2.example.com
Instance ID: prod-cluster-instance-3, Role: READER, Endpoint: prod-cluster-instance-3.example.com

Use Cases

  1. Scaling Reader Instances
    Dynamically identify and modify Reader instances based on workload requirements.
  2. Failover and DR
    Automate failover processes by targeting the Writer instance during emergencies.
  3. Tag-Based Automation
    Combine this logic with tags to perform instance-type upgrades or other cluster-wide operations.

Conclusion

Identifying RDS instance roles programmatically might seem tricky at first, but combining the WriterEndpoint from describe_db_clusters with the endpoints from describe_db_instances makes it straightforward. This approach is invaluable for automating RDS cluster management tasks.

  • AWS
  • DevOps

Continue Your Journey With…

DevOps as a Service

DevOps as a Service

Let us do the heavy lifting for you

Promotional banner
Promotional banner

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • DevOps
logo

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • AWS
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • AWS
  • DevOps
logo

Posts by Arya P B

Athena