Enabling TDE on Azure SQL DB Server using Python
Published Jun 06 2023 12:34 AM 1,394 Views

Purpose: 

Example of how-to set up TDE using BYOK on Azure SQL Database Server using Python code. 

setting up TDE using BYOK is made of two steps. 

step 1 - adding server key.

step 2 - applying the server key as encryption protector.

 

you may add more than one server key, but just one can be the encryption protector which will be used for TDE. 

Adding additional keys allows you to migrate databases from other servers that were encrypted with other keys. 

When a database first arrives on the server, the server key will be used to decrypt the database, then it will be encrypted by using the encryption protector. 

 

Example:

 

 

 

# Pre prerequisites:
# pip install azure-mgmt-sql
# pip install python-dateutil
# pip install azure-identity
# pip install azure-mgmt-resource>=18.0.0

# More examples can be found here: 
# https://github.com/Azure-Samples/azure-samples-python-management/blob/main/samples/sql/manage_server_key.py

from azure.identity import AzureCliCredential
from azure.mgmt.sql import SqlManagementClient
from azure.mgmt.sql.models import ServerKey, EncryptionProtector 

def main():

    #Setting Variables - update the values to match your environment. 
    SUBSCRIPTION_ID = ""
    GROUP_NAME = ""
    SERVER = ""
    
    #server key format must be as follows: YourVaultName_YourKeyName_YourKeyVersion
    SERVER_KEY = "x_y_z" 
    
    KeyType="AzureKeyVault"
    KeyURI="https://<KeyVaultName>.vault.azure.net/keys/<KeyName>/<KeyVersion>" # get URI from your key vault


    print("Start...")

    print("Create SqlManagementClientInstance")
    sql_client = SqlManagementClient(
        credential=AzureCliCredential(), # I am using current CLI credentials, use az login to login with your account.
        subscription_id=SUBSCRIPTION_ID
    )

    #Set TDE server key object so we can apply it to a server
    tde = ServerKey(
        server_key_type=KeyType,
        uri=KeyURI
        )
    
    server_key = sql_client.server_keys.begin_create_or_update(
        GROUP_NAME,
        SERVER,
        SERVER_KEY,
       tde
     ).result()
  
    print("Attempt to apply the server key as encryption protector... ")
    sql_client.encryption_protectors.begin_create_or_update(
        GROUP_NAME,
        SERVER,
        "current",
        {
            "server_key_name":SERVER_KEY,
            "server_key_type":KeyType
        }
    )

    print("Done")

if __name__ == "__main__":
    main()

 

 

 

 

 

Co-Authors
Version history
Last update:
‎Jun 06 2023 02:07 PM
Updated by: