tencent cloud

Secrets Manager

DokumentasiSecrets ManagerPractical TutorialApplication of Database Credentials

Application of Database Credentials

Unduh
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-10-30 17:24:02
Diterjemahkan & Diperiksa oleh AI

Application scenario

In the process of application development, the database is a basic service commonly used to store business data.
To effectively control database access permissions, applications can create database connections only when they obtain an account and password with the appropriate permissions.
To reduce the risk of account and password leakage, applications need to periodically change the account and password information used.
SSM can be applied to the above scenarios, eliminating the need for applications to frequently change usernames and passwords, and ensuring the security of business data.

SSM SDK Feature

Based on the database credential feature provided by SSM and practical tutorials on database account security management, the Tencent Cloud team has developed an SSM SDK for application integration.
By calling the SSM SDK and passing the parameters and credential name required for a database connection, an application can obtain a usable database connection without having to care about the implementation details of username and password retrieval and rotation.

Supported Language

Golang 1.13 and above.
Python 2.7 and above, Python 3 and above.

Risk Notice

When SSM periodically rotates database credentials, it updates the account and password.
Use the SSM SDK according to the SDK usage instructions. Database connection and credential information is only allowed to be used within the internal logic of the SSM SDK. Caching such data externally is prohibited to avoid database connection exceptions caused by invalid account passwords.

Prerequisites

1. You have purchased at least one cloud database instance on the Tencent Cloud platform, initialized the database, and created at least one database.
2. In the SSM console, you have created a database credential and associated it with the specified database. If you have not created a database credential, please see Create Database Credential.
3. In the CAM console, you need to complete the following two points:
A sub-account that can access SSM credential resources and MySQL instance resources has been created.
Assigned an API key to the sub-account for easy retrieval of SecretId and SecretKey for API access.

SDK Usage Instructions

Note:
You can directly download the SDK source code and use it according to the sample code provided in the source code.
1. Obtain the Go module:
(1) Run the command:
go get github.com/tencentcloud/ssm-rotation-sdk-golang/lib
(2) Import it in the Go project:
import (
_ "github.com/go-sql-driver/mysql"
"github.com/tencentcloud/ssm-rotation-sdk-golang/lib/db"
"github.com/tencentcloud/ssm-rotation-sdk-golang/lib/ssm"
)
2. Initialize the DynamicSecretRotationDb object.
dbConn := &db.DynamicSecretRotationDb{}

err := dbConn.Init(&db.Config{
DbConfig: &db.DbConfig{
MaxOpenConns: 100,
MaxIdleConns: 50,
IdleTimeoutSeconds: 100,
ReadTimeoutSeconds: 5,
WriteTimeoutSeconds: 5,
SecretName: "test", // Secret name
IpAddress: "127.0.0.1", // Access address of the database instance
Port: 58366, // Access port of the database instance
DbName: "database_name", // Database name
ParamStr: "charset=utf8&loc=Local", // Database connection configuration parameters
},
SsmServiceConfig: &ssm.SsmAccount{
SecretId: os.Getenv("SECRET_ID"), // SecretId of the sub-account
SecretKey: os.Getenv("SECRET_KEY"), // SecretKey of the sub-account
Region: "ap-guangzhou", // Region where the secret resides
},
WatchChangeInterval: time.Second * 10, // Monitoring interval. Recommended value: 10–60 seconds
})

if err != nil {
log.Fatalf("failed to initialize SSM SDK: %v", err)
}

defer func() {
if err := dbConn.Close(); err != nil {
log.Printf("failed to close SSM SDK: %v", err)
}
}()
3. Obtain a database connection.
c := dbConn.GetConn()
// Note: Call GetConn() to obtain the latest connection pool object each time you need to access the database. Do not cache this object in the business code for a long time, as this may cause database access failures!
if c == nil {
log.Fatal("failed to get database connection")
}

if err := c.Ping(); err != nil {
log.Fatalf("failed to access database: %v", err)
}
// In this example, the ping() method is called only to test the availability of the account and password. In actual business scenarios, you can perform specific database operations here.
// Perform specific database operations here.
4. Close the database connection.
c.Close() // When the application exits, you can proactively close the database connection. This is a common operation and has no direct correlation with the database credentials
1. Install the dependency packages. It is recommended to install the official SDK via pip:
pip install ssm-rotation-sdk
2. Configuration information.
import os
import logging

from ssm_rotation_sdk import (
DynamicSecretRotationDb,
Config,
DbConfig,
SsmAccount,
)

WATCH_FREQ = 10 # Credential monitoring interval. Recommended value: 10–60 seconds

db_config = DbConfig(
params={
'secret_name': 'test', # Secret name
'ip_address': '127.0.0.1', # Database address
'port': 58366, # Database port
'db_name': 'database_name', # Specify the specific database name. If it is empty, only connect to the database instance without connecting to a specific database
'param_str': 'charset=utf8&loc=Local',
}
)

ssm_service_config = SsmAccount(
params={
'secret_id': os.getenv('SECRET_ID'), # Enter the actual available sub-account SecretId
'secret_key': os.getenv('SECRET_KEY'), # Enter the actual available sub-account SecretKey
'region': 'ap-guangzhou', # Region where the secret resides
}
)

config = Config(
params={
'db_config': db_config,
'ssm_service_config': ssm_service_config,
'WATCH_FREQ': WATCH_FREQ,
}
)
3. Initialize the database object.
db_conn = DynamicSecretRotationDb()

err = db_conn.init(config)
if err:
raise RuntimeError("Failed to initialize SSM SDK: {}".format(err))
4. Obtain a database connection.
c = db_conn.get_conn()
# Note: Call GetConn() to obtain the latest DB connection each time you need to access the database. Do not cache this object in the business code, as this may cause DB access failures!
if c is None:
logging.error("Failed to get database connection")
else:
try:
c.ping(reconnect=True) # In this example, the ping() method is called only to test the availability of the account and password
# Perform specific database operations here.
except Exception:
logging.exception("Failed to access database")
raise
finally:
c.close() # Return the connection to the connection pool
5. Close the database connection.
c.close() # When the application exits, you can proactively close the database connection. This is a common operation and has no direct correlation with the database credentials







Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan