All Products
Search
Document Center

Database Autonomy Service:Best practices for automated management of column encryption rules

Last Updated:Aug 25, 2026

Database Autonomy Service (DAS) provides a toolchain for managing column encryption (data masking) rules. You can use Python scripts to create, query, and manage column encryption rules in bulk. This topic describes how to use the toolchain to automate column encryption rule management.

Toolchain overview

Use cases

Database security and compliance practices typically require the following capabilities:

  • Bulk encryption: Configure column encryption rules for sensitive columns such as phone numbers, ID card numbers, and email addresses across multiple instances, databases, and tables.

  • Query and audit: Query encrypted columns, instance activation status, quota usage, authorized users, and permission groups.

  • Policy management: Delete or update encryption policies, batch-modify authorization permissions, change encryption algorithms, and manually synchronize policies.

  • Security compliance: Replace manual console operations with auditable, traceable, and preview-enabled scripted workflows.

Toolchain architecture

The toolchain includes four Python scripts that call DAS OpenAPI through the Alibaba Cloud Python SDK V1 CommonRequest mechanism. All scripts share the same credential loading logic and support the --dry-run flag for dry-run mode.

Script

Purpose

Write operation

create_data_masking_rule.py

Create column encryption rules (core script with reusable credential and request library)

Yes

fetch_schema.py

Connect to the database, read the schema, and export a column list

No

describe_data_masking.py

Read-only queries (users, algorithms, encrypted columns, instances, status, and quota statistics)

No

manage_data_masking.py

Write operations (delete or update policies, batch-modify authorization, change algorithms, and manual sync)

Yes

Configuration files

The toolchain uses four types of configuration files. Each type provides a real file and a .example template. Each file type serves a distinct purpose:

Category

Real file

Template

Used by

Cloud API credentials

.aliyun.env

.aliyun.env.example

create / describe / manage

Database connection

mysql.conf

mysql.example.conf

fetch_schema.py

Column list (CSV)

columns.csv

columns.example.csv

create

Encryption policy (JSON)

rule.json

rule.example.json

create

Important

Real configuration files contain sensitive information. Do not commit them to version control. Keep only the *.example templates in your repository.

Applicable scope

Component

Required permissions and resources

Runtime environment

Python 3.8 or later. A venv virtual environment is recommended.

Alibaba Cloud RAM user

The RAM user must have permissions to call DAS column encryption API operations.

Network

The source IP address must be within the allowed network range for DAS column encryption operations.

Database instance

The column encryption service is activated, and column encryption quota is purchased.

Important

Column encryption is a sensitive operation. Even if the RAM policy grants the required permissions, requests from source IP addresses outside the allowlist are blocked by security risk control. Confirm the network allowlist with your security team before you proceed.

Procedure

Step 1: Download and extract the toolchain

Download the toolchain archive dbse-skills.tgz and extract it locally:

tar xzf dbsec-skills.tgz
cd dbsec-skills/skills/column-encryption-rule/scripts

Step 2: Install Python dependencies

Create a virtual environment and install dependencies:

python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt

Contents of the dependency file (requirements.txt):

aliyun-python-sdk-core>=2.16.0
PyMySQL>=1.1.0

Use the project venv for all subsequent commands: .venv/bin/python.

Step 3: Configure cloud API credentials

Copy the template and enter your AccessKey pair:

cp .aliyun.env.example .aliyun.env

Example .aliyun.env content:

ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
# Required only for STS temporary credentials. Delete or leave empty for standard AccessKey pairs.
ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
Important

This file contains real credentials. Store it securely and never share it.

Step 4: Prepare the encryption policy template

Copy the rule template:

cp rule.example.json rule.json

Keep rule.json as a shared policy template and move all instance-specific information to columns.csv:

{
  "ProductId": 5,
  "EncAlgorithm": "AES_128_GCM",
  "EncryptionKeyMode": "client_key",
  "CooperationChannel": "DAS",
  "BackendRegionId": "cn-zhangjiakou",
  "UserList": [
    {
      "AccountId": "shared_user",
      "AuthRole": "fullAccess",
      "EngineType": "MySQL"
    },
    {
      "AccountId": "only_for_instanceB",
      "InstanceId": "rm-instanceB",
      "AuthRole": "restrictedAccess",
      "EngineType": "MySQL"
    }
  ],
  "ResourceGroupId": ""
}

Key fields:

Field

Description

ProductId

Database product type. The value 5 represents RDS MySQL. For a single-product policy, keep this field at the top level. For a cross-product policy, specify it per row in columns.csv.

EncAlgorithm

Encryption algorithm, such as AES_128_GCM or AES_256_GCM.

EncryptionKeyMode

Encryption key mode, such as client_key.

CooperationChannel

Set to DAS.

BackendRegionId

Backend processing region. Set to cn-zhangjiakou.

UserList

Authorized user list. Set AccountId to the database account name (not the cloud account). If you omit InstanceId, the account is a shared user. If you specify InstanceId, the user applies only to that instance.

AuthRole values:

Value

Description

fullAccess

Can view plaintext data

restrictedAccess

Can view only ciphertext, and can decrypt with a user key

noneAccess

Can view only ciphertext and cannot decrypt

Note

Do not include InstanceId or ServiceRegionId at the top level. Specify these fields per row in the CSV file.

Step 5: Prepare the column list

You can prepare the column list in either of the following ways:

Method 1: Manually create columns.csv

Copy the template:

cp columns.example.csv columns.csv

Enter data one column per row. Example:

RegionId,InstanceId,DbName,TableName,Column,EngineType,ProductId
cn-hangzhou,rm-instanceA,your_database,your_table,email,MySQL,
cn-hangzhou,rm-instanceA,your_database,your_table,phone,MySQL,
cn-beijing,rm-instanceB,another_db,users,id_card,MySQL,

To specify multiple columns for the same table, use the Columns field with comma-separated values in quotes:

RegionId,InstanceId,DbName,TableName,Columns,EngineType
cn-hangzhou,rm-instanceA,your_database,your_table,"email,phone",MySQL

The ProductId column is optional. Specify it for cross-product scenarios. If left empty, the top-level value from rule.json is used.

Method 2: Automatically export with fetch_schema.py

Copy the template and enter your database connection information:

cp mysql.example.conf mysql.conf

Example mysql.conf content (key:value format):

url:rm-xxxxxxxxxxxxxxxxx.rwlb.rds.aliyuncs.com
user:your_user
pass:your_password

View the database schema (text format):

.venv/bin/python fetch_schema.py --config mysql.conf --database your_database

Export a compatible columns.csv file:

.venv/bin/python fetch_schema.py --config mysql.conf --database your_database \
  --format csv --region-id cn-beijing --instance-id rm-xxxxxxxxxxxxxxxxx > columns.csv
Note

--region-id and --instance-id are required in CSV mode because they are cloud resource identifiers that cannot be obtained from the database schema. After export, edit columns.csv to keep only the sensitive columns that require encryption.

Full parameter list for fetch_schema.py:

--config          Database configuration file. Default: mysql.conf
--database        Query only the specified database. Repeatable. Omit to enumerate all business databases.
--include-system  Include system databases (information_schema, etc.)
--format          json | text | csv. Default: text
--region-id       Required for CSV: instance region, e.g. cn-beijing
--instance-id     Required for CSV: instance ID, e.g. rm-xxxx
--engine-type     EngineType for CSV. Default: MySQL

Step 6: Perform a dry run

Always perform a dry run before you submit changes to verify the request body and batch splitting.

Dry run for a single creation (without CSV):

.venv/bin/python create_data_masking_rule.py \
  --env-file .aliyun.env --config rule.json --dry-run

Dry run for batch creation (with CSV):

.venv/bin/python create_data_masking_rule.py \
  --env-file .aliyun.env --config rule.json --columns-csv columns.csv --dry-run

Example dry-run output:

BatchCount: number of batches
TotalSubRuleCount: aggregated table rule count
TotalUniqueColumnCount: unique column count
Batches: InstanceId, ServiceRegionId, SubRuleCount, UniqueColumnCount per batch

Optional: local quota precheck. For example, if the remaining quota is 50 columns:

.venv/bin/python create_data_masking_rule.py \
  --env-file .aliyun.env --config rule.json --columns-csv columns.csv \
  --max-new-columns 50 --dry-run

If the column count exceeds the --max-new-columns limit, the script stops locally without sending requests.

Step 7: Create column encryption rules

After the dry run succeeds, remove the --dry-run flag to execute the operation.

Single creation:

.venv/bin/python create_data_masking_rule.py \
  --env-file .aliyun.env --config rule.json

Batch creation:

.venv/bin/python create_data_masking_rule.py \
  --env-file .aliyun.env --config rule.json --columns-csv columns.csv

Optional: adjust the number of SubRules per batch (maximum 100):

.venv/bin/python create_data_masking_rule.py \
  --env-file .aliyun.env --config rule.json --columns-csv columns.csv --batch-size 50
Important

The script automatically groups rules by RegionId + InstanceId + ProductId and splits each instance into independent requests with up to 100 SubRuleList entries per batch. Do not combine multiple instances into a single request. Otherwise, rules may be created successfully but the instance may still appear grayed out in the asset center.

Step 8: Query and verify

Use describe_data_masking.py to query column encryption status. Use --action to select a read-only API operation. All operations support --dry-run.

Operation (--action)

Description

Required parameters

DescribeDataMaskingUsers

Authorized users and permission groups

None

DescribeDataMaskingAlgorithms

Supported encryption algorithms for the instance

--product-id / --service-region-id / --instance-id

ListDataMaskingColumns

Encrypted column list (supports pagination and multi-dimensional filtering)

Optional filter parameters

ListDataMaskingInstances

Column encryption instance list (supports pagination and multi-dimensional filtering)

Optional filter parameters

CheckDataMaskingInstance

Column encryption activation status for the instance

--product-id / --service-region-id / --instance-id

GetDataMaskingColumnCount

Encrypted column count and quota statistics

--product-ids

GetDataMaskingAccountCount

Authorized account count statistics

None

Examples:

# List authorized users
.venv/bin/python describe_data_masking.py --env-file .aliyun.env \
  --action DescribeDataMaskingUsers

# Query supported encryption algorithms for an instance
.venv/bin/python describe_data_masking.py --env-file .aliyun.env \
  --action DescribeDataMaskingAlgorithms \
  --product-id 5 --service-region-id cn-beijing --instance-id rm-xxxxxxxxxxxxxxxxx

# Query encrypted columns with pagination
.venv/bin/python describe_data_masking.py --env-file .aliyun.env \
  --action ListDataMaskingColumns \
  --product-ids 5 --db-name your_database --page-size 20 --current-page 1

# Get encrypted column quota statistics
.venv/bin/python describe_data_masking.py --env-file .aliyun.env \
  --action GetDataMaskingColumnCount --product-ids 5

Filter and pagination parameters for List operations: --masking-status, --template-id, --risk-level-id, --model-tag-id, --instance-id, --db-name, --table-name, --column-name, --current-page, --page-size, --product-id, --product-ids, --risk-level-ids, --template-rule-ids, --engine-type.

Step 9: Management operations

Use manage_data_masking.py with --action to select a write API operation. All operations support --dry-run to preview the request body. List parameters are provided through a JSON file specified by --config. Scalar parameters can be set in the config file or overridden by CLI options (CLI takes precedence).

Operation (--action)

Description

Notes

DeleteDataMaskingRule

Delete an encryption policy

SubRuleList[].ProductId is an integer (int64)

ModifyDataMaskingRule

Update an encryption policy

SubRuleList[].ProductId is a string. RegionId/ProductId/InstanceId/DbName/TableName/ColumnsName are required

BatchModifyDataMaskingUsers

Batch-modify authorization permission groups

--auth-role is required. Provide UserList in the config file

ModifyDataMaskingEncryptionAlgorithm

Change the encryption algorithm for an instance

Specify --instance-id/--product-id/--service-region-id/--encryption-algorithm

ManualSyncMaskingRules

Manually synchronize all encryption policies

No business parameters

Examples (run with --dry-run first to preview, then remove --dry-run to execute):

# Delete a policy: provide SubRuleList in config. ProductId is an integer.
.venv/bin/python manage_data_masking.py --env-file .aliyun.env \
  --action DeleteDataMaskingRule --config delete_rule.json --rule-name rule-demo --dry-run

# Batch-modify authorization permission groups
.venv/bin/python manage_data_masking.py --env-file .aliyun.env \
  --action BatchModifyDataMaskingUsers --config batch_users.json \
  --auth-role fullAccess --dry-run

# Change the encryption algorithm for an instance
.venv/bin/python manage_data_masking.py --env-file .aliyun.env \
  --action ModifyDataMaskingEncryptionAlgorithm \
  --instance-id rm-xxx --product-id 5 --service-region-id cn-beijing \
  --encryption-algorithm AES_256_GCM --dry-run

# Manually synchronize all encryption policies (no business parameters)
.venv/bin/python manage_data_masking.py --env-file .aliyun.env \
  --action ManualSyncMaskingRules --dry-run

Workflow quick reference

The complete workflow consists of six steps:

1. Prepare credentials    cp .aliyun.env.example .aliyun.env     # Enter AK/SK for DAS OpenAPI
2. Prepare rule template  cp rule.example.json rule.json         # Configure the shared encryption policy
3. Prepare column list    Write columns.csv manually, or use fetch_schema.py to export
4. Dry run                Add --dry-run to verify the request body and batches
5. Execute                Remove --dry-run to execute
6. Verify results         Use describe_data_masking.py to query and verify

Default API configuration

The scripts use the following DAS API configuration by default:

Domain:             das.cn-shanghai.aliyuncs.com
Version:             2020-01-16
Action:              CreateDataMaskingRule
Method:             POST / HTTPS
RegionId:            cn-shanghai (POP access region. Do not modify.)
CooperationChannel:  DAS
BackendRegionId:     cn-zhangjiakou
Important

RegionId: cn-shanghai is the access region used by the Python SDK and POP requests. It differs from the business-level ServiceRegionId. Specify the region of the instance to encrypt through ServiceRegionId and SubRuleList[].RegionId (for example, cn-hangzhou for Hangzhou or cn-beijing for Beijing).

Security best practices

  • Credential management: .aliyun.env, mysql.conf, rule.json, and columns.csv contain real credentials or business data. Do not commit them to version control. Keep only *.example templates in your repository.

  • Least privilege: Grant the RAM user only the permissions required for DAS column encryption API operations. Use STS temporary credentials when possible.

  • Network access control: Column encryption is a sensitive operation. Make sure that the source IP address is within the allowed network range for DAS.

  • Dry run before execution: All write operations (create and manage) support --dry-run. Always perform a dry run before you submit changes.

  • Quota precheck: Before batch execution, verify TotalUniqueColumnCount in the dry-run output. Use --max-new-columns for local quota protection when necessary.

  • Operation audit: The scripts call DAS through OpenAPI. All operations can be audited through ActionTrail.

FAQ

  • Q: The dry run passes, but the actual creation returns 401 Deny. What do I do?

    A: The dry run only validates the local request body. It does not guarantee server-side acceptance. Common causes of 401 Deny: the RAM user associated with the AccessKey pair lacks permissions to call DAS column encryption API operations; the source IP address is not in the allowlist; the AccessKey pair is blocked by security policies. Troubleshooting: verify that the RAM policy grants the required Action permissions; contact the security team with the RequestID, AccessKey pair, and source IP address; or retry with an AccessKey pair that has the required permissions and is within the allowed network range.

  • Q: Some batches fail during batch creation. What do I do?

    A: If the quota is exceeded, the API returns sale_instance_quota_exception. The script indicates which batch failed. Previously successful batches are not automatically rolled back. Before batch execution, verify TotalUniqueColumnCount in the dry-run output and use --max-new-columns for local quota protection when necessary.

  • Q: Should I include InstanceId in rule.json?

    A: Do not include it. Keep rule.json as a shared policy template and provide all instance-specific information in columns.csv. This way, a single rule.json can be reused with CSV files for any instance. To scale to multiple instances, modify only the CSV file without changing rule.json.

  • Q: How do I configure different authorization for multiple instances in UserList?

    A: Use InstanceId to differentiate: if InstanceId is omitted, the user is a shared user and applies to every instance with instance information backfilled; if InstanceId is specified, the user applies only to batches matching that instance, and other batches automatically filter the user out. No nested structure is required.

  • Q: Why does the CSV exported by fetch_schema.py not include RegionId and InstanceId?

    A: RegionId, InstanceId, and EngineType are cloud resource identifiers that cannot be obtained from the database schema. In CSV mode, --region-id and --instance-id are required. After export, edit columns.csv to keep only the sensitive columns that require encryption.

  • Q: After BatchModifyDataMaskingUsers changes authorization, the same account appears in two permission groups. Is this normal?

    A: After authorization changes, DescribeDataMaskingUsers may temporarily show the same account in two groups with SyncStatus=1 (synchronizing). After synchronization completes (SyncStatus=0), only the target group remains. This is expected asynchronous server-side synchronization and requires no script handling. Re-query after a short wait to verify the final state.

  • Q: ModifyDataMaskingRule returns InvalidParameter for custom column encryption rules. What do I do?

    A: The ModifyDataMaskingRule operation is designed for template-based rules. For custom column encryption rules created by CreateDataMaskingRule (RuleId=0), this operation returns InvalidParameter "InstanceId". This is a business constraint, not a script defect. To update custom column encryption rules, delete them first and then re-create them.