[Python] Python SqlManagementClient Azure MSAL Login: Add Firewall Rules Programmatically Not...

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    In Python notebook, I want to connect to my Azure SQL DB using MSAL. In the second step, after logging in successfully, I need to configure the firewall by adding the public IP to the Firewall settings:

    from msal import PublicClientApplication
    from azure.identity import DefaultAzureCredential
    from azure.mgmt.sql import SqlManagementClient
    ....

    def add_firewall_rule(public_ip):
    def add_firewall_rule(public_ip):
    credential = DefaultAzureCredential()
    sql_client = SqlManagementClient(credential, subscription_id)

    firewall_rule = sql_client.firewall_rules.create_or_update(
    resource_group_name=resource_group_name,
    server_name=sql_server_name,
    firewall_rule_name=firewall_rule_name,
    parameters={
    "start_ip_address": public_ip,
    "end_ip_address": public_ip,
    }
    )

    ...

    app = PublicClientApplication(client_id, authority=f"https://login.microsoftonline.com/{tenant_id}")
    result = app.acquire_token_interactive(scopes=["https://database.windows.net/.default"])

    # Add the public IP address to the SQL server firewall rule
    firewall_rule = add_firewall_rule(public_ip)

    conn = pyodbc.connect(
    f"DRIVER={{ODBC Driver 18 for SQL Server}};"
    f"SERVER={server};"
    f"DATABASE={database};"
    f"Encrypt=yes;" # Critical for Azure connections
    f"TrustServerCertificate=no;"
    f"AccessToken={token};"
    )
    print("Connected successfully!")
    ...


    But I got


    Error: 'SqlManagementClient' object has no attribute 'firewall_rules'
    ​

    Also tried other way like:

    firewall_rule = sql_client.firewall_rules.create_or_update(
    resource_group_name,
    sql_server_name,
    firewall_rule_name,
    {
    'start_ip_address': public_ip,
    'end_ip_address': public_ip
    }
    )


    But I'm still getting the same error with no luck... As a last check, all packages are the latest. Guess it's a coding issue rather than a credential problem, as the credential works when used in Azure Data Studio.

    I have read through the references:

    1. https://learn.microsoft.com/en-us/p...ns.azurefirewallsoperations?view=azure-python
    2. https://learn.microsoft.com/en-us/python/api/azure-mgmt-sql/azure.mgmt.sql.models?view=azure-python

    Continue reading...

Compartilhe esta Página