-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathparser.go
More file actions
1197 lines (1010 loc) · 38.7 KB
/
parser.go
File metadata and controls
1197 lines (1010 loc) · 38.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package project
import (
"azureaiagent/internal/pkg/agents/agent_yaml"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/appcontainers/armappcontainers"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/authorization/armauthorization/v3"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices/v2"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
"github.com/azure/azure-dev/cli/azd/pkg/azdext"
"github.com/azure/azure-dev/cli/azd/pkg/graphsdk"
"github.com/braydonk/yaml"
"github.com/google/uuid"
)
type FoundryParser struct {
AzdClient *azdext.AzdClient
}
// Check if there is a service using containerapp host and contains agent.yaml file in the service path
func shouldRun(ctx context.Context, project *azdext.ProjectConfig) (bool, error) {
projectPath := project.Path
for _, service := range project.Services {
if service.Host == "containerapp" {
servicePath := filepath.Join(projectPath, service.RelativePath)
agentYamlPath := filepath.Join(servicePath, "agent.yaml")
agentYmlPath := filepath.Join(servicePath, "agent.yml")
agentPath := ""
if _, err := os.Stat(agentYamlPath); err == nil {
agentPath = agentYamlPath
}
if _, err := os.Stat(agentYmlPath); err == nil {
agentPath = agentYmlPath
}
if agentPath != "" {
// read the file content into bytes and close the file
content, err := os.ReadFile(agentPath)
if err != nil {
return false, fmt.Errorf("failed to read agent yaml file: %w", err)
}
err = agent_yaml.ValidateAgentDefinition(content)
if err != nil {
return false, fmt.Errorf("agent.yaml is not valid to run: %w", err)
}
var genericTemplate map[string]any
if err := yaml.Unmarshal(content, &genericTemplate); err != nil {
return false, fmt.Errorf("YAML content is not valid to run: %w", err)
}
kind, ok := genericTemplate["kind"].(string)
if !ok {
return false, fmt.Errorf("kind field is not a valid string to check should run: %w", err)
}
return kind == string(agent_yaml.AgentKindHosted), nil
}
}
}
return false, nil
}
func (p *FoundryParser) SetIdentity(ctx context.Context, args *azdext.ProjectEventArgs) error {
shouldRun, err := shouldRun(ctx, args.Project)
if err != nil {
return fmt.Errorf("failed to determine if extension should attach: %w", err)
}
if !shouldRun {
return nil
}
// Get aiFoundryProjectResourceId from environment config
azdEnvClient := p.AzdClient.Environment()
response, err := azdEnvClient.GetConfigString(ctx, &azdext.GetConfigStringRequest{
Path: "infra.parameters.aiFoundryProjectResourceId",
})
if err != nil {
return fmt.Errorf("failed to get environment config: %w", err)
}
aiFoundryProjectResourceID := response.Value
fmt.Println("✓ Retrieved aiFoundryProjectResourceId")
// Extract subscription ID from resource ID
parts := strings.Split(aiFoundryProjectResourceID, "/")
if len(parts) < 3 {
return fmt.Errorf("invalid resource ID format: %s", aiFoundryProjectResourceID)
}
// Find subscription ID
var subscriptionID string
for i, part := range parts {
if part == "subscriptions" && i+1 < len(parts) {
subscriptionID = parts[i+1]
break
}
}
if subscriptionID == "" {
return fmt.Errorf("subscription ID not found in resource ID: %s", aiFoundryProjectResourceID)
}
// Get the tenant ID
tenantResponse, err := p.AzdClient.Account().LookupTenant(ctx, &azdext.LookupTenantRequest{
SubscriptionId: subscriptionID,
})
if err != nil {
return fmt.Errorf("failed to get tenant ID: %w", err)
}
cred, err := azidentity.NewAzureDeveloperCLICredential(&azidentity.AzureDeveloperCLICredentialOptions{
TenantID: tenantResponse.TenantId,
AdditionallyAllowedTenants: []string{"*"},
})
if err != nil {
return fmt.Errorf("failed to create Azure credential: %w", err)
}
// Get Microsoft Foundry Project's managed identity
fmt.Println("Retrieving Microsoft Foundry Project identity...")
projectPrincipalID, err := getProjectPrincipalID(ctx, cred, aiFoundryProjectResourceID, subscriptionID)
if err != nil {
return fmt.Errorf("failed to get Project principal ID: %w", err)
}
fmt.Printf("Principal ID: %s\n", projectPrincipalID)
// Get Application ID from Principal ID
fmt.Println("Retrieving Application ID...")
projectClientID, err := getApplicationID(ctx, cred, projectPrincipalID)
if err != nil {
return fmt.Errorf("failed to get Application ID: %w", err)
}
fmt.Printf("Application ID: %s\n", projectClientID)
// Save to environment
cResponse, err := azdEnvClient.GetCurrent(ctx, &azdext.EmptyRequest{})
if err != nil {
return fmt.Errorf("failed to get current environment: %w", err)
}
_, err = azdEnvClient.SetValue(ctx, &azdext.SetEnvRequest{
EnvName: cResponse.Environment.Name,
Key: "AZURE_AI_PROJECT_PRINCIPAL_ID",
Value: projectClientID,
})
if err != nil {
return fmt.Errorf("failed to set AZURE_AI_PROJECT_PRINCIPAL_ID in environment: %w", err)
}
fmt.Println("✓ Application ID saved to environment")
return nil
}
// getProjectPrincipalID retrieves the principal ID from the Microsoft Foundry Project using Azure SDK
func getProjectPrincipalID(
ctx context.Context,
cred *azidentity.AzureDeveloperCLICredential,
resourceID,
subscriptionID string) (string, error) {
// Create resources client
client, err := armresources.NewClient(subscriptionID, cred, nil)
if err != nil {
return "", fmt.Errorf("failed to create resources client: %w", err)
}
// Get the resource
// API version for Microsoft Foundry projects (Machine Learning workspaces)
apiVersion := "2025-06-01"
resp, err := client.GetByID(ctx, resourceID, apiVersion, nil)
if err != nil {
return "", fmt.Errorf("failed to retrieve resource: %w", err)
}
// Extract principal ID from identity
if resp.Identity == nil {
return "", fmt.Errorf("resource does not have an identity")
}
if resp.Identity.PrincipalID == nil {
return "", fmt.Errorf("resource identity does not have a principal ID")
}
principalID := *resp.Identity.PrincipalID
if principalID == "" {
return "", fmt.Errorf("principal ID is empty")
}
return principalID, nil
}
// getApplicationID retrieves the application ID from the principal ID using Microsoft Graph API
func getApplicationID(
ctx context.Context, cred *azidentity.AzureDeveloperCLICredential, principalID string) (string, error) {
// Create Graph client
graphClient, err := graphsdk.NewGraphClient(cred, nil)
if err != nil {
return "", fmt.Errorf("failed to create Graph client: %w", err)
}
// Get service principal directly by object ID (principal ID)
servicePrincipal, err := graphClient.
ServicePrincipalById(principalID).
Get(ctx)
if err != nil {
return "", fmt.Errorf("failed to retrieve service principal with principal ID '%s': %w", principalID, err)
}
appID := servicePrincipal.AppId
if appID == "" {
return "", fmt.Errorf("application ID is empty")
}
return appID, nil
}
// getCognitiveServicesAccountLocation retrieves the location of a Cognitive Services account using Azure SDK
func getCognitiveServicesAccountLocation(
ctx context.Context,
cred *azidentity.AzureDeveloperCLICredential,
subscriptionID,
resourceGroupName,
accountName string) (string, error) {
// Create cognitive services accounts client
client, err := armcognitiveservices.NewAccountsClient(subscriptionID, cred, nil)
if err != nil {
return "", fmt.Errorf("failed to create cognitive services client: %w", err)
}
// Get the account
resp, err := client.Get(ctx, resourceGroupName, accountName, nil)
if err != nil {
return "", fmt.Errorf("failed to get cognitive services account: %w", err)
}
// Extract location
if resp.Location == nil {
return "", fmt.Errorf("cognitive services account does not have a location")
}
location := *resp.Location
if location == "" {
return "", fmt.Errorf("location is empty")
}
return location, nil
}
/////////////////////////////////////////////////////////////////////////////
// Config structures for JSON parsing
type AgentRegistrationPayload struct {
Description string `json:"description"`
Definition AgentDefinition `json:"definition"`
}
type AgentDefinition struct {
Kind string `json:"kind"`
ContainerProtocolVersions []ContainerProtocolVersion `json:"container_protocol_versions"`
ContainerAppResourceID string `json:"container_app_resource_id"`
IngressSubdomainSuffix string `json:"ingress_subdomain_suffix"`
}
type ContainerProtocolVersion struct {
Protocol string `json:"protocol"`
Version string `json:"version"`
}
type AgentResponse struct {
Version string `json:"version"`
}
type DataPlanePayload struct {
Agent AgentReference `json:"agent"`
Input string `json:"input"`
Stream bool `json:"stream"`
}
type AgentReference struct {
Type string `json:"type"`
Name string `json:"name"`
Version string `json:"version"`
}
type DataPlaneResponse struct {
Output string `json:"output"`
}
func (p *FoundryParser) CoboPostDeploy(ctx context.Context, args *azdext.ProjectEventArgs) error {
shouldRun, err := shouldRun(ctx, args.Project)
if err != nil {
return fmt.Errorf("failed to determine if extension should attach: %w", err)
}
if !shouldRun {
return nil
}
azdEnvClient := p.AzdClient.Environment()
cEnvResponse, err := azdEnvClient.GetCurrent(ctx, &azdext.EmptyRequest{})
if err != nil {
return fmt.Errorf("failed to get current environment: %w", err)
}
envResponse, err := azdEnvClient.GetValues(ctx, &azdext.GetEnvironmentRequest{
Name: cEnvResponse.Environment.Name,
})
if err != nil {
return fmt.Errorf("failed to get environment values: %w", err)
}
values := envResponse.KeyValues
azdEnv := make(map[string]string, len(values))
for _, kv := range values {
azdEnv[kv.Key] = kv.Value
}
// Get required values from azd environment
containerAppPrincipalID := azdEnv["SERVICE_API_IDENTITY_PRINCIPAL_ID"]
aiFoundryProjectResourceID := azdEnv["AZURE_AI_PROJECT_ID"]
deploymentName := azdEnv["DEPLOYMENT_NAME"]
resourceID := azdEnv["SERVICE_API_RESOURCE_ID"]
agentName := azdEnv["AGENT_NAME"]
//aiProjectEndpoint := azdEnv["AI_PROJECT_ENDPOINT"]
// Validate required variables
if err := validateRequired("AZURE_AI_PROJECT_ID", aiFoundryProjectResourceID); err != nil {
return err
}
// Extract project information from resource IDs
parts := strings.Split(aiFoundryProjectResourceID, "/")
if len(parts) < 11 {
fmt.Fprintln(os.Stderr, "Error: Invalid Microsoft Foundry Project Resource ID format")
os.Exit(1)
}
// Extract AI account resource ID by removing "/projects/project-name" from the project resource ID
parts = strings.Split(aiFoundryProjectResourceID, "/projects/")
aiAccountResourceId := parts[0]
if err := validateRequired("AZURE_AI_PROJECT_ID", aiFoundryProjectResourceID); err != nil {
return err
}
if err := validateRequired("SERVICE_API_IDENTITY_PRINCIPAL_ID", containerAppPrincipalID); err != nil {
return err
}
if err := validateRequired("DEPLOYMENT_NAME", deploymentName); err != nil {
return err
}
if err := validateRequired("AGENT_NAME", agentName); err != nil {
return err
}
projectSubscriptionID := parts[2]
projectResourceGroup := parts[4]
projectAIFoundryName := parts[8]
projectName := parts[10]
// Get the tenant ID
tenantResponse, err := p.AzdClient.Account().LookupTenant(ctx, &azdext.LookupTenantRequest{
SubscriptionId: projectSubscriptionID,
})
if err != nil {
return fmt.Errorf("failed to get tenant ID: %w", err)
}
cred, err := azidentity.NewAzureDeveloperCLICredential(&azidentity.AzureDeveloperCLICredentialOptions{
TenantID: tenantResponse.TenantId,
AdditionallyAllowedTenants: []string{"*"},
})
if err != nil {
return fmt.Errorf("failed to create Azure credential: %w", err)
}
// Get Microsoft Foundry region using SDK
aiFoundryRegion, err := getCognitiveServicesAccountLocation(
ctx, cred, projectSubscriptionID, projectResourceGroup, projectAIFoundryName)
if err != nil {
return fmt.Errorf("failed to get Microsoft Foundry region: %w", err)
}
fmt.Printf("Microsoft Foundry region: %s\n", aiFoundryRegion)
fmt.Printf("Project: %s\n", projectName)
fmt.Printf("Deployment: %s\n", deploymentName)
fmt.Printf("Agent: %s\n", agentName)
// Assign Azure AI User role
if err := assignAzureAIRole(ctx, cred, containerAppPrincipalID, aiAccountResourceId); err != nil {
fmt.Fprintf(os.Stderr, "Error: Failed to assign 'Azure AI User' role: %v\n", err)
fmt.Fprintln(os.Stderr, "This requires Owner or User Access Administrator role on the Microsoft Foundry Account.")
fmt.Fprintln(os.Stderr, "Manual command:")
fmt.Fprintf(os.Stderr, "az role assignment create \\\n")
fmt.Fprintf(os.Stderr, " --assignee %s \\\n", containerAppPrincipalID)
fmt.Fprintf(os.Stderr, " --role \"53ca6127-db72-4b80-b1b0-d745d6d5456d\" \\\n")
fmt.Fprintf(os.Stderr, " --scope \"%s\"\n", aiAccountResourceId)
return err
}
if err := validateRequired("SERVICE_API_RESOURCE_ID", resourceID); err != nil {
return err
}
// Deactivate hello-world revision
if err := deactivateHelloWorldRevision(ctx, cred, resourceID); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to deactivate hello-world revision: %v\n", err)
// Don't return error, just warn - this is not critical for the deployment
}
// Verify authentication configuration
if err := verifyAuthConfiguration(ctx, cred, resourceID); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to verify authentication configuration: %v\n", err)
// Don't return error, just warn - this is not critical for the deployment
}
// Get the Container App endpoint (FQDN) for testing using SDK
fmt.Println("Retrieving Container App endpoint...")
acaEndpoint, err := getContainerAppEndpoint(ctx, cred, resourceID, projectSubscriptionID)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to retrieve Container App endpoint: %v\n", err)
} else {
fmt.Printf("Container App endpoint: %s\n", acaEndpoint)
}
// Get Microsoft Foundry Project endpoint using SDK
fmt.Println("Retrieving Microsoft Foundry Project API endpoint...")
aiFoundryProjectEndpoint, err := getAIFoundryProjectEndpoint(
ctx, cred, aiFoundryProjectResourceID, projectSubscriptionID)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to retrieve Microsoft Foundry Project API endpoint: %v\n", err)
} else {
fmt.Printf("Microsoft Foundry Project API endpoint: %s\n", aiFoundryProjectEndpoint)
}
// Acquire AAD token using SDK
token, err := getAccessToken(ctx, cred, "https://ai.azure.com")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: Failed to acquire access token: %v\n", err)
return fmt.Errorf("failed to acquire access token: %w", err)
}
// Get latest revision and build ingress suffix using SDK
latestRevision, err := getLatestRevisionName(ctx, cred, resourceID, projectSubscriptionID)
if err != nil {
return fmt.Errorf("failed to get latest revision: %w", err)
}
ingressSuffix := "--" + latestRevision[strings.LastIndex(latestRevision, "--")+2:]
if ingressSuffix == "--"+latestRevision {
ingressSuffix = "--" + latestRevision
}
// Construct agent registration URI
workspaceName := fmt.Sprintf("%s@%s@AML", projectAIFoundryName, projectName)
apiPath := fmt.Sprintf(
"/agents/v2.0/subscriptions/%s/resourceGroups/%s/providers/Microsoft.MachineLearningServices/"+
"workspaces/%s/agents/%s/versions?api-version=2025-05-15-preview",
projectSubscriptionID, projectResourceGroup, workspaceName, agentName)
uri := ""
if aiFoundryProjectEndpoint != "" {
uri = aiFoundryProjectEndpoint + apiPath
} else {
uri = fmt.Sprintf("https://%s.api.azureml.ms%s", aiFoundryRegion, apiPath)
}
// Register agent with retry logic
agentVersion := registerAgent(ctx, uri, token, resourceID, ingressSuffix)
// Test authentication and agent
if agentVersion != "" {
testUnauthenticatedAccess(ctx, acaEndpoint)
testDataPlane(ctx, aiFoundryProjectEndpoint, token, agentName, agentVersion)
}
// Print Azure Portal link
fmt.Println()
fmt.Println("======================================")
fmt.Println("Azure Portal")
fmt.Println("======================================")
fmt.Printf("https://portal.azure.com/#@/resource%s\n", resourceID)
fmt.Println()
fmt.Println("✓ Post-deployment completed successfully")
return nil
}
// validateRequired checks if a required variable is set
func validateRequired(name, value string) error {
if value == "" {
return fmt.Errorf("%s not set", name)
}
return nil
}
// assignAzureAIRole assigns the Azure AI User role to the container app identity using Azure SDK
func assignAzureAIRole(ctx context.Context, cred *azidentity.AzureDeveloperCLICredential, principalID, scope string) error {
fmt.Println()
fmt.Println("======================================")
fmt.Println("Assigning Azure AI Access Permissions")
fmt.Println("======================================")
roleDefinitionID := "53ca6127-db72-4b80-b1b0-d745d6d5456d" // Azure AI User
fmt.Println("Assigning 'Azure AI User' role to Container App identity...")
fmt.Printf("Principal ID: %s\n", principalID)
fmt.Printf("Scope: %s\n", scope)
fmt.Println()
// Extract subscription ID from scope
// Scope format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/...
parts := strings.Split(scope, "/")
var subscriptionID string
for i, part := range parts {
if part == "subscriptions" && i+1 < len(parts) {
subscriptionID = parts[i+1]
break
}
}
if subscriptionID == "" {
return fmt.Errorf("could not extract subscription ID from scope: %s", scope)
}
// Create role assignments client
client, err := armauthorization.NewRoleAssignmentsClient(subscriptionID, cred, nil)
if err != nil {
return fmt.Errorf("failed to create role assignments client: %w", err)
}
// Construct full role definition ID
fullRoleDefinitionID := fmt.Sprintf("%s/providers/Microsoft.Authorization/roleDefinitions/%s", scope, roleDefinitionID)
// Check if the role assignment already exists
// Use atScope() to list all role assignments at this scope, then filter in code
pager := client.NewListForScopePager(scope, &armauthorization.RoleAssignmentsClientListForScopeOptions{
Filter: new("atScope()"),
})
assignmentExists := false
var existingAssignmentId string
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return fmt.Errorf("failed to list role assignments: %w", err)
}
for _, assignment := range page.Value {
if assignment.Properties != nil &&
assignment.Properties.PrincipalID != nil &&
assignment.Properties.RoleDefinitionID != nil {
// Filter by both principal ID and role definition ID
if *assignment.Properties.PrincipalID == principalID &&
*assignment.Properties.RoleDefinitionID == fullRoleDefinitionID {
assignmentExists = true
if assignment.Name != nil {
existingAssignmentId = *assignment.Name
}
break
}
}
}
if assignmentExists {
break
}
}
if assignmentExists {
fmt.Println("✓ Role assignment already exists")
if existingAssignmentId != "" {
fmt.Printf(" Assignment ID: %s\n", existingAssignmentId)
}
} else {
// Generate a unique name for the role assignment
roleAssignmentName := uuid.New().String()
// Create role assignment
parameters := armauthorization.RoleAssignmentCreateParameters{
Properties: &armauthorization.RoleAssignmentProperties{
RoleDefinitionID: new(fullRoleDefinitionID),
PrincipalID: new(principalID),
},
}
resp, err := client.Create(ctx, scope, roleAssignmentName, parameters, nil)
if err != nil {
// Check if the error is due to role assignment already existing (409 Conflict)
if strings.Contains(err.Error(), "RoleAssignmentExists") || strings.Contains(err.Error(), "409") {
fmt.Println("✓ Role assignment already exists (detected during creation)")
assignmentExists = true // Mark as existing so we skip waiting
} else {
return fmt.Errorf("failed to create role assignment: %w", err)
}
} else {
fmt.Println("✓ Successfully assigned 'Azure AI User' role")
if resp.Name != nil {
fmt.Printf(" Assignment ID: %s\n", *resp.Name)
}
}
}
// Only wait for propagation if we just created a new assignment
if !assignmentExists {
fmt.Println()
fmt.Println("⏳ Waiting 30 seconds for RBAC propagation...")
time.Sleep(30 * time.Second)
// Validate the assignment
fmt.Println("Validating role assignment...")
pager = client.NewListForScopePager(scope, &armauthorization.RoleAssignmentsClientListForScopeOptions{
Filter: new("atScope()"),
})
validated := false
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "Warning: Could not validate role assignment. It may still be propagating.")
break
}
for _, assignment := range page.Value {
if assignment.Properties != nil && assignment.Properties.RoleDefinitionID != nil {
if strings.Contains(*assignment.Properties.RoleDefinitionID, roleDefinitionID) {
fmt.Println("✓ Role assignment validated successfully")
fmt.Printf(" Role: Azure AI User\n")
validated = true
break
}
}
}
if validated {
break
}
}
if !validated {
fmt.Fprintln(os.Stderr, "Warning: Could not validate role assignment. It may still be propagating.")
}
}
return nil
}
// deactivateHelloWorldRevision deactivates the hello-world placeholder revision using Azure SDK
func deactivateHelloWorldRevision(
ctx context.Context, cred *azidentity.AzureDeveloperCLICredential, resourceID string) error {
fmt.Println()
fmt.Println("======================================")
fmt.Println("Deactivating Hello-World Revision")
fmt.Println("======================================")
fmt.Println("ℹ️ Azure Container Apps requires an image during provision, but with remote Docker")
fmt.Println(" build, the app image doesn't exist yet. A hello-world placeholder image is used")
fmt.Println(" during 'azd provision', then replaced with your app image during 'azd deploy'.")
fmt.Println(" Now that your app is deployed, we'll deactivate the placeholder revision.")
fmt.Println()
// Parse resource ID
parsedResource, err := arm.ParseResourceID(resourceID)
if err != nil {
return fmt.Errorf("failed to parse resource ID: %w", err)
}
subscription := parsedResource.SubscriptionID
resourceGroup := parsedResource.ResourceGroupName
appName := parsedResource.Name
if subscription == "" || resourceGroup == "" || appName == "" {
return fmt.Errorf("could not parse subscription, resource group or app name from resource ID: %s", resourceID)
}
// Create container apps revisions client
revisionsClient, err := armappcontainers.NewContainerAppsRevisionsClient(subscription, cred, nil)
if err != nil {
return fmt.Errorf("failed to create revisions client: %w", err)
}
// List all revisions
pager := revisionsClient.NewListRevisionsPager(resourceGroup, appName, nil)
var helloWorldRevision *armappcontainers.Revision
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return fmt.Errorf("failed to list revisions: %w", err)
}
for _, revision := range page.Value {
// Check if this is a hello-world revision
if revision.Properties != nil &&
revision.Properties.Template != nil &&
revision.Properties.Template.Containers != nil &&
len(revision.Properties.Template.Containers) > 0 {
container := revision.Properties.Template.Containers[0]
if container.Image != nil &&
strings.Contains(*container.Image, "containerapps-helloworld") &&
revision.Name != nil &&
!strings.Contains(*revision.Name, "--azd-") {
helloWorldRevision = revision
break
}
}
}
if helloWorldRevision != nil {
break
}
}
if helloWorldRevision == nil {
fmt.Println("No hello-world revision found (already removed or using custom image)")
return nil
}
if helloWorldRevision.Name == nil {
return fmt.Errorf("revision name is nil")
}
revisionName := *helloWorldRevision.Name
fmt.Printf("Found hello-world revision: %s\n", revisionName)
if helloWorldRevision.Properties != nil &&
helloWorldRevision.Properties.Template != nil &&
helloWorldRevision.Properties.Template.Containers != nil &&
len(helloWorldRevision.Properties.Template.Containers) > 0 {
if img := helloWorldRevision.Properties.Template.Containers[0].Image; img != nil {
fmt.Printf("Image: %s\n", *img)
}
}
// Double-check before deactivating
if helloWorldRevision.Properties != nil &&
helloWorldRevision.Properties.Template != nil &&
helloWorldRevision.Properties.Template.Containers != nil &&
len(helloWorldRevision.Properties.Template.Containers) > 0 {
container := helloWorldRevision.Properties.Template.Containers[0]
if container.Image == nil || !strings.Contains(*container.Image, "containerapps-helloworld") {
fmt.Fprintln(os.Stderr, "Warning: Revision does not have hello-world image, skipping for safety")
return nil
}
}
if strings.Contains(revisionName, "--azd-") {
fmt.Fprintln(os.Stderr, "Warning: Revision name contains '--azd-' pattern, skipping for safety")
return nil
}
// Check if already inactive
if helloWorldRevision.Properties != nil &&
helloWorldRevision.Properties.Active != nil &&
!*helloWorldRevision.Properties.Active {
fmt.Println("Revision is already inactive")
return nil
}
// Deactivate the revision
fmt.Println("Deactivating revision...")
_, err = revisionsClient.DeactivateRevision(ctx, resourceGroup, appName, revisionName, nil)
if err != nil {
return fmt.Errorf("failed to deactivate revision: %w", err)
}
fmt.Println("✓ Hello-world revision deactivated successfully")
return nil
}
// verifyAuthConfiguration verifies the authentication configuration using Azure SDK
func verifyAuthConfiguration(ctx context.Context, cred *azidentity.AzureDeveloperCLICredential, resourceID string) error {
fmt.Println()
fmt.Println("======================================")
fmt.Println("Verifying Authentication Configuration")
fmt.Println("======================================")
// Parse resource ID
parsedResource, err := arm.ParseResourceID(resourceID)
if err != nil {
return fmt.Errorf("failed to parse resource ID: %w", err)
}
subscription := parsedResource.SubscriptionID
resourceGroup := parsedResource.ResourceGroupName
appName := parsedResource.Name
if subscription == "" || resourceGroup == "" || appName == "" {
return fmt.Errorf("could not parse subscription, resource group or app name from resource ID: %s", resourceID)
}
// Create container apps auth configs client
authClient, err := armappcontainers.NewContainerAppsAuthConfigsClient(subscription, cred, nil)
if err != nil {
return fmt.Errorf("failed to create auth configs client: %w", err)
}
// Get the auth config (named "current" by convention for the active config)
authConfig, err := authClient.Get(ctx, resourceGroup, appName, "current", nil)
if err != nil {
fmt.Fprintln(os.Stderr, "Warning: No authentication configuration found")
return nil
}
// Check if Azure AD authentication is configured
if authConfig.Properties == nil ||
authConfig.Properties.Platform == nil ||
authConfig.Properties.Platform.Enabled == nil {
fmt.Fprintln(os.Stderr, "Warning: No authentication configuration found")
return nil
}
if !*authConfig.Properties.Platform.Enabled {
fmt.Fprintln(os.Stderr, "Warning: Authentication is not enabled")
return nil
}
// Check for Azure AD identity provider
if authConfig.Properties.IdentityProviders != nil &&
authConfig.Properties.IdentityProviders.AzureActiveDirectory != nil &&
authConfig.Properties.IdentityProviders.AzureActiveDirectory.Enabled != nil &&
*authConfig.Properties.IdentityProviders.AzureActiveDirectory.Enabled {
fmt.Println("✓ Azure AD authentication enabled")
aadConfig := authConfig.Properties.IdentityProviders.AzureActiveDirectory
if aadConfig.Registration != nil && aadConfig.Registration.ClientID != nil {
fmt.Printf(" Client ID: %s\n", *aadConfig.Registration.ClientID)
}
if authConfig.Properties.GlobalValidation != nil &&
authConfig.Properties.GlobalValidation.UnauthenticatedClientAction != nil {
fmt.Printf(
" Unauthenticated Action: %s\n",
string(*authConfig.Properties.GlobalValidation.UnauthenticatedClientAction))
}
} else {
fmt.Fprintln(os.Stderr, "Warning: Azure AD authentication is not configured")
}
return nil
}
// getContainerAppEndpoint retrieves the Container App FQDN using Azure SDK
func getContainerAppEndpoint(
ctx context.Context,
cred *azidentity.AzureDeveloperCLICredential,
resourceID,
subscriptionID string) (string, error) {
// Parse resource ID
parsedResource, err := arm.ParseResourceID(resourceID)
if err != nil {
return "", fmt.Errorf("failed to parse resource ID: %w", err)
}
resourceGroup := parsedResource.ResourceGroupName
appName := parsedResource.Name
if resourceGroup == "" || appName == "" {
return "", fmt.Errorf("could not parse resource group or app name from resource ID: %s", resourceID)
}
// Create container apps client
client, err := armappcontainers.NewContainerAppsClient(subscriptionID, cred, nil)
if err != nil {
return "", fmt.Errorf("failed to create container apps client: %w", err)
}
// Get the container app
containerApp, err := client.Get(ctx, resourceGroup, appName, nil)
if err != nil {
return "", fmt.Errorf("failed to get container app: %w", err)
}
// Extract FQDN
if containerApp.Properties == nil ||
containerApp.Properties.Configuration == nil ||
containerApp.Properties.Configuration.Ingress == nil ||
containerApp.Properties.Configuration.Ingress.Fqdn == nil {
return "", fmt.Errorf("container app does not have an ingress FQDN")
}
fqdn := *containerApp.Properties.Configuration.Ingress.Fqdn
if fqdn == "" {
return "", fmt.Errorf("FQDN is empty")
}
return "https://" + fqdn, nil
}
// getAIFoundryProjectEndpoint retrieves the Microsoft Foundry Project API endpoint using Azure SDK
func getAIFoundryProjectEndpoint(
ctx context.Context,
cred *azidentity.AzureDeveloperCLICredential,
resourceID,
subscriptionID string) (string, error) {
// Create resources client
client, err := armresources.NewClient(subscriptionID, cred, nil)
if err != nil {
return "", fmt.Errorf("failed to create resources client: %w", err)
}
// Get the resource
// API version for Microsoft Foundry projects (Machine Learning workspaces)
apiVersion := "2025-06-01"
resp, err := client.GetByID(ctx, resourceID, apiVersion, nil)
if err != nil {
return "", fmt.Errorf("failed to retrieve resource: %w", err)
}
// Extract Microsoft Foundry API endpoint
if resp.Properties == nil {
return "", fmt.Errorf("resource does not have properties")
}
// Parse properties as a map to access nested endpoints
propsMap, ok := resp.Properties.(map[string]any)
if !ok {
return "", fmt.Errorf("failed to parse resource properties")
}
endpoints, ok := propsMap["endpoints"].(map[string]any)
if !ok {
return "", fmt.Errorf("resource does not have endpoints")
}
aiFoundryAPI, ok := endpoints["AI Foundry API"].(string)
if !ok || aiFoundryAPI == "" {
return "", fmt.Errorf("AI Foundry API endpoint not found")
}
return aiFoundryAPI, nil
}
// getAccessToken retrieves an access token for the specified resource using Azure SDK
func getAccessToken(ctx context.Context, cred *azidentity.AzureDeveloperCLICredential, resource string) (string, error) {
// Get access token for the specified resource
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{resource + "/.default"},
})
if err != nil {
return "", fmt.Errorf("failed to get access token: %w", err)
}
return token.Token, nil
}
// getLatestRevisionName retrieves the latest revision name for a Container App using Azure SDK
func getLatestRevisionName(
ctx context.Context,
cred *azidentity.AzureDeveloperCLICredential,
resourceID,
subscriptionID string) (string, error) {
// Parse resource ID
parsedResource, err := arm.ParseResourceID(resourceID)
if err != nil {
return "", fmt.Errorf("failed to parse resource ID: %w", err)
}
resourceGroup := parsedResource.ResourceGroupName
appName := parsedResource.Name
if resourceGroup == "" || appName == "" {
return "", fmt.Errorf("could not parse resource group or app name from resource ID: %s", resourceID)
}
// Create container apps client
client, err := armappcontainers.NewContainerAppsClient(subscriptionID, cred, nil)
if err != nil {
return "", fmt.Errorf("failed to create container apps client: %w", err)
}
// Get the container app
containerApp, err := client.Get(ctx, resourceGroup, appName, nil)
if err != nil {
return "", fmt.Errorf("failed to get container app: %w", err)
}
// Extract latest revision name
if containerApp.Properties == nil || containerApp.Properties.LatestRevisionName == nil {
return "", fmt.Errorf("container app does not have a latest revision name")
}
latestRevision := *containerApp.Properties.LatestRevisionName
if latestRevision == "" {