Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Create a database administrator account

You are already using a managed Identity to connect to the Azure Container Registry. You can use this same identity to also connect to the database. This will allow you to remove the username and password from the config repository.

Step by step guidance

  1. You will need to allow the user assigned managed identity access to the database. To configure this, you will need to first make your current logged in user account database administrator. For this to work on a MySQL database you first need an additional managed identity.

    DB_ADMIN_USER_ASSIGNED_IDENTITY_NAME=uid-dbadmin-$APPNAME-$UNIQUEID
       
    ADMIN_IDENTITY_RESOURCE_ID=$(az identity create \
       --name $DB_ADMIN_USER_ASSIGNED_IDENTITY_NAME \
       --resource-group $RESOURCE_GROUP \
       --query id \
       --output tsv)
    
  2. This identity needs to be assigned to your MySQL server.

    az mysql flexible-server identity assign \
        --resource-group $RESOURCE_GROUP \
        --server-name $MYSQL_SERVER_NAME \
        --identity $DB_ADMIN_USER_ASSIGNED_IDENTITY_NAME
    
    
    az mysql flexible-server identity list \
        --resource-group $RESOURCE_GROUP \
        --server-name $MYSQL_SERVER_NAME 
    
  3. Get the current logged in user and object ID. This will give you the info of the user account you are currently logged in with in the Azure CLI.

    CURRENT_USER=$(az account show --query user.name --output tsv)
    echo $CURRENT_USER
    CURRENT_USER_OBJECTID=$(az ad signed-in-user show --query id --output tsv)
    echo $CURRENT_USER_OBJECTID
    
  4. Next you create a database administrator based on your current user account.

    az mysql flexible-server ad-admin create \
        --resource-group $RESOURCE_GROUP \
        --server-name $MYSQL_SERVER_NAME \
        --object-id $CURRENT_USER_OBJECTID \
        --display-name $CURRENT_USER \
        --identity $DB_ADMIN_USER_ASSIGNED_IDENTITY_NAME
    
    DB_ID=$(az mysql flexible-server db show \
         --server-name $MYSQL_SERVER_NAME \
         --resource-group $RESOURCE_GROUP \
         -d $DATABASE_NAME \
         --query id \
         -o tsv)