Skip to content

Commit 8e47674

Browse files
Refactor scripts for improved logging and error handling; remove redundant code and streamline role assignments in Azure CLI scripts
1 parent ea9960e commit 8e47674

13 files changed

+199
-501
lines changed

documents/DeploymentGuide.md

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ If you're not using one of the above options for opening the project, then you'l
147147
1. Make sure the following tools are installed:
148148
- [PowerShell](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.5) <small>(v7.0+)</small> - available for Windows, macOS, and Linux.
149149
- [Azure Developer CLI (azd)](https://aka.ms/install-azd) <small>(v1.18.0+)</small> - version
150-
- [Python 3.9 to 3.11](https://www.python.org/downloads/)
150+
- [Python 3.9+](https://www.python.org/downloads/)
151151
- [Docker Desktop](https://www.docker.com/products/docker-desktop/)
152152
- [Git](https://git-scm.com/downloads)
153153
- [Microsoft ODBC Driver 18](https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver16) for SQL Server.
@@ -248,7 +248,32 @@ Once you've opened the project in [Codespaces](#github-codespaces), [Dev Contain
248248
- This deployment generally takes **7-10 minutes** to provision the resources in your account and set up the solution.
249249
- If you encounter an error or timeout during deployment, changing the location may help, as there could be availability constraints for the resources.
250250
251-
5. Once the deployment has completed successfully and you would like to use the **sample data**, please open a **Git Bash terminal** and run the bash command printed below. The bash command will look like the following:
251+
5. Once the deployment has completed successfully, copy the bash command from terminal: (ex: `bash ./infra/scripts/process_sample_data.sh`) for later use.
252+
253+
> **Note**: If you are running this deployment in GitHub Codespaces or VS Code Dev Container or Visual Studio Code (WEB) skip to step 7.
254+
255+
6. Create and activate a virtual environment in bash terminal:
256+
257+
```shell
258+
python -m venv .venv
259+
```
260+
261+
```shell
262+
source .venv/Scripts/activate
263+
```
264+
265+
7. Login to Azure:
266+
267+
```shell
268+
az login
269+
```
270+
271+
Alternatively, login to Azure using a device code (recommended when using VS Code Web):
272+
273+
```shell
274+
az login --use-device-code
275+
```
276+
8. Run the bash script from the output of the azd deployment. The script will look like the following:
252277
253278
```bash
254279
bash ./infra/scripts/process_sample_data.sh
@@ -267,9 +292,9 @@ Once you've opened the project in [Codespaces](#github-codespaces), [Dev Contain
267292
<CU-Endpoint> <AI-Agent-Endpoint> <CU-API-Version>
268293
```
269294

270-
6. Once the deployment has completed successfully, open the [Azure Portal](https://portal.azure.com/), go to the deployed resource group, find the App Service, and get the app URL from `Default domain`.
295+
9. Once the deployment has completed successfully, open the [Azure Portal](https://portal.azure.com/), go to the deployed resource group, find the App Service, and get the app URL from `Default domain`.
271296

272-
7. You can now delete the resources by running `azd down`, if you are done trying out the application.
297+
10. You can now delete the resources by running `azd down`, if you are done trying out the application.
273298
> **Note:** If you deployed with `enableRedundancy=true` and Log Analytics workspace replication is enabled, you must first disable replication before running `azd down` else resource group delete will fail. Follow the steps in [Handling Log Analytics Workspace Deletion with Replication Enabled](./LogAnalyticsReplicationDisable.md), wait until replication returns `false`, then run `azd down`.
274299

275300
### 🛠️ Troubleshooting

documents/LocalDebuggingSetup.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Install these tools before you start:
1111
- [Azure Tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack)
1212
- [Bicep](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-bicep)
1313
- [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python)
14-
- [Python 3.9 to 3.11](https://www.python.org/downloads/). **Important:** Check "Add Python to PATH" during installation.
14+
- [Python 3.9+](https://www.python.org/downloads/). **Important:** Check "Add Python to PATH" during installation.
1515
- [PowerShell 7.0+](https://github.com/PowerShell/PowerShell#get-powershell).
1616
- [Node.js (LTS)](https://nodejs.org/en).
1717
- [Git](https://git-scm.com/downloads).

infra/scripts/add_user_scripts/assign_sql_roles.py

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -55,24 +55,18 @@ def assign_sql_roles(server, database, roles_json):
5555
credential = AzureCliCredential()
5656

5757
# Connect to SQL Server
58-
print(f"Connecting to {server}/{database}...")
5958
conn = connect_with_token(server, database, credential)
6059
cursor = conn.cursor()
6160

62-
print("Connected successfully.")
63-
6461
# Process each role assignment
6562
for role_assignment in roles:
6663
client_id = role_assignment.get("clientId")
6764
display_name = role_assignment.get("displayName")
6865
role = role_assignment.get("role")
6966

7067
if not client_id or not display_name or not role:
71-
print(f"Skipping invalid role assignment: {role_assignment}")
7268
continue
7369

74-
print(f"\nProcessing: {display_name} -> {role}")
75-
7670
# Check if user already exists
7771
check_user_sql = f"SELECT COUNT(*) FROM sys.database_principals WHERE name = '{display_name}'"
7872
cursor.execute(check_user_sql)
@@ -81,16 +75,13 @@ def assign_sql_roles(server, database, roles_json):
8175
if not user_exists:
8276
# Create user from external provider
8377
create_user_sql = f"CREATE USER [{display_name}] FROM EXTERNAL PROVIDER"
84-
print(f" Creating user: {display_name}")
8578
try:
8679
cursor.execute(create_user_sql)
8780
conn.commit()
88-
print(" ✓ User created successfully")
81+
print(f"✓ Created user: {display_name}")
8982
except Exception as e:
90-
print(f" ✗ Failed to create user: {e}")
83+
print(f"✗ Failed to create user: {e}")
9184
continue
92-
else:
93-
print(f" User already exists: {display_name}")
9485

9586
# Check if user already has the role
9687
check_role_sql = f"""
@@ -106,21 +97,17 @@ def assign_sql_roles(server, database, roles_json):
10697
if not has_role:
10798
# Add user to role
10899
add_role_sql = f"ALTER ROLE [{role}] ADD MEMBER [{display_name}]"
109-
print(f" Assigning role: {role}")
110100
try:
111101
cursor.execute(add_role_sql)
112102
conn.commit()
113-
print(" ✓ Role assigned successfully")
103+
print(f"✓ Assigned {role} to {display_name}")
114104
except Exception as e:
115-
print(f" ✗ Failed to assign role: {e}")
105+
print(f"✗ Failed to assign {role}: {e}")
116106
continue
117-
else:
118-
print(f" User already has role: {role}")
119107

120108
# Close connection
121109
cursor.close()
122110
conn.close()
123-
print("\n✓ All role assignments completed successfully")
124111
return 0
125112

126113
except Exception as e:

infra/scripts/copy_kb_files.sh

Lines changed: 18 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,6 @@ extractedFolder1="call_transcripts"
1111
zipFileName2="infra/data/audio_data.zip"
1212
extractedFolder2="audio_data"
1313

14-
echo "Script Started"
15-
echo "Storage Account: $storageAccountName"
16-
echo "Container Name: $containerName"
17-
echo "Resource Group: $resourceGroupName"
18-
1914
# Validate required parameters
2015
if [ -z "$storageAccountName" ] || [ -z "$containerName" ] || [ -z "$resourceGroupName" ]; then
2116
echo "Error: Missing required parameters."
@@ -25,102 +20,76 @@ fi
2520

2621
# Extract zip files if they exist
2722
if [ -f "$zipFileName1" ]; then
28-
echo "Extracting $zipFileName1..."
29-
unzip -o "$zipFileName1" -d "$extractedFolder1"
30-
else
31-
echo "Warning: $zipFileName1 not found. Skipping extraction."
23+
unzip -q -o "$zipFileName1" -d "$extractedFolder1"
3224
fi
3325

3426
if [ -f "$zipFileName2" ]; then
35-
echo "Extracting $zipFileName2..."
36-
unzip -o "$zipFileName2" -d "$extractedFolder2"
37-
else
38-
echo "Warning: $zipFileName2 not found. Skipping extraction."
27+
unzip -q -o "$zipFileName2" -d "$extractedFolder2"
3928
fi
4029

4130
# Authenticate with Azure
42-
if az account show &> /dev/null; then
43-
echo "Already authenticated with Azure."
44-
else
31+
if ! az account show &> /dev/null; then
4532
echo "Authenticating with Azure CLI..."
46-
az login
33+
az login --use-device-code
4734
fi
4835

4936
# Check and assign Storage Blob Data Contributor role to current user
50-
echo "Checking Storage Blob Data Contributor role assignment..."
5137
signed_user_id=$(az ad signed-in-user show --query id --output tsv)
5238
storage_resource_id=$(az storage account show --name "$storageAccountName" --resource-group "$resourceGroupName" --query id --output tsv)
5339

5440
role_assignment=$(MSYS_NO_PATHCONV=1 az role assignment list --assignee $signed_user_id --role "Storage Blob Data Contributor" --scope $storage_resource_id --query "[].roleDefinitionId" -o tsv)
5541
if [ -z "$role_assignment" ]; then
56-
echo "Assigning Storage Blob Data Contributor role to current user..."
42+
echo "Assigning Storage Blob Data Contributor role"
5743
MSYS_NO_PATHCONV=1 az role assignment create --assignee $signed_user_id --role "Storage Blob Data Contributor" --scope $storage_resource_id --output none
58-
if [ $? -eq 0 ]; then
59-
echo "Storage Blob Data Contributor role assigned successfully."
60-
# Wait a bit for role assignment to propagate
61-
echo "Waiting for role assignment to propagate..."
62-
sleep 10
63-
else
64-
echo "Failed to assign Storage Blob Data Contributor role."
44+
if [ $? -ne 0 ]; then
45+
echo "✗ Failed to assign Storage Blob Data Contributor role"
6546
exit 1
6647
fi
67-
else
68-
echo "User already has Storage Blob Data Contributor role."
48+
sleep 10
6949
fi
7050

7151
# Upload files to storage account
72-
# Using az storage blob upload-batch to upload files with Azure CLI authentication
73-
echo "Uploading call transcripts to storage account..."
7452
if [ -d "$extractedFolder1" ]; then
53+
echo "✓ Uploading call transcripts"
7554
az storage blob upload-batch \
7655
--account-name "$storageAccountName" \
7756
--destination "$containerName/$extractedFolder1" \
7857
--source "$extractedFolder1" \
7958
--auth-mode login \
8059
--pattern '*' \
81-
--overwrite
82-
if [ $? -eq 0 ]; then
83-
echo "✓ Call transcripts uploaded successfully"
84-
else
60+
--overwrite \
61+
--output none
62+
if [ $? -ne 0 ]; then
8563
echo "✗ Failed to upload call transcripts"
8664
exit 1
8765
fi
88-
else
89-
echo "Warning: $extractedFolder1 directory not found. Skipping upload."
9066
fi
9167

92-
echo "Uploading audio data to storage account..."
9368
if [ -d "$extractedFolder2" ]; then
69+
echo "✓ Uploading audio data"
9470
az storage blob upload-batch \
9571
--account-name "$storageAccountName" \
9672
--destination "$containerName/$extractedFolder2" \
9773
--source "$extractedFolder2" \
9874
--auth-mode login \
9975
--pattern '*' \
100-
--overwrite
101-
if [ $? -eq 0 ]; then
102-
echo "✓ Audio data uploaded successfully"
103-
else
76+
--overwrite \
77+
--output none
78+
if [ $? -ne 0 ]; then
10479
echo "✗ Failed to upload audio data"
10580
exit 1
10681
fi
107-
else
108-
echo "Warning: $extractedFolder2 directory not found. Skipping upload."
10982
fi
11083

11184
# Create custom data directories for user uploads
112-
echo "Creating custom data directories..."
11385
az storage fs directory create \
11486
--account-name "$storageAccountName" \
11587
--file-system "$containerName" \
11688
--name custom_audiodata \
117-
--auth-mode login 2>/dev/null || echo "custom_audiodata directory may already exist"
89+
--auth-mode login --output none 2>/dev/null
11890

11991
az storage fs directory create \
12092
--account-name "$storageAccountName" \
12193
--file-system "$containerName" \
12294
--name custom_transcripts \
123-
--auth-mode login 2>/dev/null || echo "custom_transcripts directory may already exist"
124-
125-
echo "✓ Custom data directories created successfully"
126-
echo "Script completed successfully"
95+
--auth-mode login --output none 2>/dev/null

infra/scripts/index_scripts/01_create_search_index.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,6 @@
3030

3131
INDEX_NAME = "call_transcripts_index"
3232

33-
print("calling create_search_index()....")
34-
35-
3633
def create_search_index():
3734
"""
3835
Creates or updates an Azure Cognitive Search index configured for:
@@ -105,7 +102,7 @@ def create_search_index():
105102
)
106103

107104
result = index_client.create_or_update_index(index)
108-
print(f"Search index '{result.name}' created or updated successfully.")
105+
print(f"Search index '{result.name}' created")
109106

110107

111108
create_search_index()

infra/scripts/index_scripts/02_create_cu_template_audio.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@
3636
analyzer = client.get_analyzer_detail_by_id(ANALYZER_ID)
3737
if analyzer is not None:
3838
client.delete_analyzer(ANALYZER_ID)
39-
except Exception as e:
40-
print(f"Analyzer with ID {ANALYZER_ID} was not found. Proceeding to create a new one.")
39+
except Exception:
40+
pass
4141

4242
response = client.begin_create_analyzer(ANALYZER_ID, analyzer_template_path=ANALYZER_TEMPLATE_FILE)
4343
result = client.poll_result(response)
44-
print(f"Analyzer with ID {ANALYZER_ID} created successfully.")
44+
print(f"Analyzer '{ANALYZER_ID}' created")

infra/scripts/index_scripts/02_create_cu_template_text.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@
3131
analyzer = client.get_analyzer_detail_by_id(ANALYZER_ID)
3232
if analyzer is not None:
3333
client.delete_analyzer(ANALYZER_ID)
34-
except Exception as e:
35-
print(f"Analyzer with ID {ANALYZER_ID} was not found. Proceeding to create a new one.")
34+
except Exception:
35+
pass
3636

3737
response = client.begin_create_analyzer(ANALYZER_ID, analyzer_template_path=ANALYZER_TEMPLATE_FILE)
3838
result = client.poll_result(response)
39-
print(f"Analyzer with ID {ANALYZER_ID} created successfully.")
39+
print(f"Analyzer '{ANALYZER_ID}' created")

0 commit comments

Comments
 (0)