Search code examples
mysqlboto3amazon-rdsmysql-connector-pythonmoto

How can I connect to a moto mysql instance?


I created an RDS DB Instance using a mocked boto3 rds client. Here's how I set it up in my conftest.py

@pytest.fixture
def aws_credentials():
    """Mocked AWS Credentials for moto."""
    os.environ["AWS_ACCESS_KEY_ID"] = "testing"
    os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
    os.environ["AWS_SECURITY_TOKEN"] = "testing"
    os.environ["AWS_SESSION_TOKEN"] = "testing"

@pytest.fixture
def rds_client(aws_credentials, aws_region):
    with mock_rds():
        client = boto3.client("rds", region_name=aws_region)
        yield client

Following the example here (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.Python.html) I set up my mysql connector like this:

db_instance = rds_client.create_db_instance(DBInstanceIdentifier="TestDBInstanceIdentifier",
                                            DBInstanceClass="db.m4.large", Engine="mysql",
                                            MasterUsername="root", DBName="TestDBName")
print("RDS Instance-----------------------------------------------------")
print(db_instance)

host = db_instance['DBInstance']['Endpoint']['Address']
port = db_instance['DBInstance']['Endpoint']['Port']
user = db_instance['DBInstance']['MasterUsername']
dbname = db_instance['DBInstance']['DBName']
print("Starting connection")
token = rds_client.generate_db_auth_token(DBHostname=host, Port=port, DBUsername=user, Region=aws_region)

mydb = mysql.connector.connect(host=host, database=dbname, user=user, passwd=token, port=port)

However, the connector can't find the DB:

FAILED test_read_rds_db - mysql.connector.errors.DatabaseError: 2005 (HY000): Unknown MySQL server host 'TestDBInstanceIdentifier.aaaaaaaaaa.us-east-1.rds.amazonaws.com' (8)

Has someone been able to set this up before?


Solution

  • Moto does not offer this functionality. It mocks the AWS API, but does not expose any RDBMS-functionality.

    You could look into Localstack instead. It uses Moto in the background to mock calls to AWS, but offers features on top of that such as the ability to connect to an RDS instance. See the docs here: https://docs.localstack.cloud/aws/rds/