tencent cloud

Secrets Manager

DocumentaçãoSecrets ManagerPractical TutorialApplication of Database Credentials

Application of Database Credentials

Baixar
Modo Foco
Tamanho da Fonte
Última atualização: 2026-09-07 17:51:24
Traduzido por IA

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 (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 command: go get github.com/tencentcloud/ssm-rotation-sdk-golang/lib
(2) Import it in the Go project:
import (
"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", // Credential name
IpAddress: "127.0.0.1", // Access address of the database instance
Port: 58366, // Access port of the database instance
DbName: "database_name", // Specifies the specific database name; if empty, only connects to the database instance without connecting to a specific database
ParamStr: "charset=utf8&loc=Local", // Database connection configuration parameters
},
SsmServiceConfig: &ssm.SsmAccount{
SecretId: os.Getenv("secret_id"), // Sub-account's SecretId
SecretKey: os.Getenv("secret_key"), // Sub-account's SecretKey
Region: "ap-guangzhou", // Select the region where the credentials are actually stored. Please fill in according to the actual situation. The example given is the Guangzhou region.
},
WatchChangeInterval: time.Second * 10, // Interval for monitoring changes in credential content. Typically, the interval is set between 10 seconds and 60 seconds
})
3. Obtain a database connection.
```golang
c := dbConn.GetConn() // Warning: You must call GetConn() to obtain the latest DB connection every time you access the database. Do not cache this object in your business code to avoid DB access failures!
if err := c.Ping(); err != nil { // This example simply uses the ping() method to test the availability of the account password. In actual business, you can perform specific db operations here.
log.Fatal("failed to access db with err: ", err)
return
}
```
4. Close the database connection.
```golang
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.
```shell
pip install -r requirements.txt
```
2. Configuration information.
```python
WATCH_FREQ = 10 # Interval for monitoring changes in credential content, usually set between 10 to 60 seconds
db_config = DbConfig(
params={
'secret_name': "test", # Credential name
'ip_address': "127.0.0.1", # Database address
'port': 58366, # Database port
'db_name': "database_name", # Specify the actual database name, if empty, then only connect to the database instance, not a specific database
'param_str': "charset=utf8&loc=Local",
})
ssm_service_config = SsmAccount(
params={
'secret_id': os.getenv('SECRET_ID'), # You must fill in the actual usable SecretId
'secret_key': os.getenv('SECRET_KEY'), # You must fill in the actual usable SecretKey
'url': test_url,
'region': "ap-guangzhou" # Region where the credential is stored
})
config = Config(
params={
'db_config': db_config,
'ssm_service_config': ssm_service_config,
'WATCH_FREQ': WATCH_FREQ
})
```
3. Initialize the database object.
```python
db_conn = DynamicSecretRotationDb()
err = db_conn.init(config)
```
4. Obtain a database connection.
```python
c = db_conn.get_conn() # Warning: You must call GetConn() to obtain the most recent DB connection every time you access the database. Do not cache this object in your business code to avoid DB access failures!
try:
c.ping() # This example simply uses the ping() method to test the availability of the account password. In actual business, you can perform specific DB operations here.
except TencentCloudSDKException as e:
logging.error("failed to access db with err: {0}".format(str(
e.args[0])).encode("utf-8"))
```
5. Close the database connection.
```python
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
```







Ajuda e Suporte

Esta página foi útil?

comentários