1313from azure .cli .command_modules .acs .azuremonitormetrics .helper import sanitize_resource_id
1414
1515
16+ # pylint: disable=line-too-long
1617def link_grafana_instance (cmd , raw_parameters , azure_monitor_workspace_resource_id ):
17- from azure .cli .core .util import send_raw_request
18+ from azure .cli .command_modules .acs ._client_factory import get_resources_client
19+ resources = get_resources_client (cmd .cli_ctx , raw_parameters .get ("subscription_id" ))
1820 # GET grafana principal ID
1921 try :
2022 grafana_resource_id = raw_parameters .get ("grafana_resource_id" )
2123 if grafana_resource_id is None or grafana_resource_id == "" :
2224 return GrafanaLink .NOPARAMPROVIDED
2325 grafana_resource_id = sanitize_resource_id (grafana_resource_id )
24- grafanaURI = "{0}{1}?api-version={2}" .format (
25- cmd .cli_ctx .cloud .endpoints .resource_manager ,
26- grafana_resource_id ,
27- GRAFANA_API
28- )
29- headers = ['User-Agent=azuremonitormetrics.link_grafana_instance' ]
30- grafanaArmResponse = send_raw_request (cmd .cli_ctx , "GET" , grafanaURI , body = {}, headers = headers )
26+ grafanaArmResponse = resources .get_by_id (grafana_resource_id , GRAFANA_API )
3127
3228 # Check if 'identity' and 'type' exist in the response
33- identity_info = grafanaArmResponse . json (). get ( "identity" , {})
34- identity_type = identity_info . get ( "type" , "" ).lower ()
29+ identity_info = getattr ( grafanaArmResponse , "identity" , {})
30+ identity_type = getattr ( identity_info , "type" , "" ).lower () if identity_info else ""
3531
3632 if identity_type == "systemassigned" :
37- servicePrincipalId = identity_info . get ( "principalId" )
33+ servicePrincipalId = getattr ( identity_info , "principal_id" , None )
3834 elif identity_type == "userassigned" :
39- user_assigned_identities = identity_info . get ( "userAssignedIdentities " , {})
35+ user_assigned_identities = getattr ( identity_info , "user_assigned_identities " , {})
4036 if not user_assigned_identities :
4137 raise CLIError ("No user-assigned identities found." )
42- servicePrincipalId = list (user_assigned_identities .values ())[0 ]["principalId" ]
38+ user_assigned_values = list (user_assigned_identities .values ())
39+ if not user_assigned_values or "principal_id" not in user_assigned_values [0 ]:
40+ raise CLIError ("Invalid user-assigned identity structure or missing principal_id." )
41+ servicePrincipalId = user_assigned_values [0 ]["principal_id" ]
4342 else :
4443 raise CLIError ("Unsupported or missing identity type." )
4544
4645 if not servicePrincipalId :
4746 raise CLIError ("No service principal ID found for the specified identity." )
48- except CLIError as e :
47+ except Exception as e :
4948 raise CLIError (e )
5049 # Add Role Assignment
5150 try :
5251 MonitoringDataReader = "b0d8363b-8ddd-447d-831f-62ca05bff136"
53- roleDefinitionURI = "{0}{1}/providers/Microsoft.Authorization/roleAssignments/{2}?api-version={3}" .format (
54- cmd .cli_ctx .cloud .endpoints .resource_manager ,
55- azure_monitor_workspace_resource_id ,
56- uuid .uuid4 (),
57- GRAFANA_ROLE_ASSIGNMENT_API
52+ roleAssignmentId = str (uuid .uuid4 ())
53+ roleDefinitionId = (
54+ f"{ azure_monitor_workspace_resource_id } /providers/Microsoft.Authorization/roleDefinitions/"
55+ f"{ MonitoringDataReader } "
5856 )
59- roleDefinitionId = "{0}/providers/Microsoft.Authorization/roleDefinitions/{1}" . format (
60- azure_monitor_workspace_resource_id ,
61- MonitoringDataReader
57+ roleAssignmentResourceId = (
58+ f" { azure_monitor_workspace_resource_id } /providers/Microsoft.Authorization/roleAssignments/"
59+ f" { roleAssignmentId } "
6260 )
63- association_body = json . dumps ( {
61+ association_body = {
6462 "properties" : {
6563 "roleDefinitionId" : roleDefinitionId ,
6664 "principalId" : servicePrincipalId
6765 }
68- })
69- headers = ['User-Agent=azuremonitormetrics.add_role_assignment' ]
70- send_raw_request (cmd .cli_ctx , "PUT" , roleDefinitionURI , body = association_body , headers = headers )
71- except CLIError as e :
72- if e .response .status_code != 409 :
73- erroString = "Role Assingment failed. Please manually assign the `Monitoring Data Reader` role\
74- to the Azure Monitor Workspace ({0}) for the Azure Managed Grafana\
75- System Assigned Managed Identity ({1})" .format (
76- azure_monitor_workspace_resource_id ,
77- servicePrincipalId
66+ }
67+ try :
68+ resources .begin_create_or_update_by_id (
69+ roleAssignmentResourceId ,
70+ GRAFANA_ROLE_ASSIGNMENT_API ,
71+ association_body
7872 )
79- print (erroString )
73+ except CLIError as e :
74+ # If already exists (409), ignore, else print error
75+ if not (hasattr (e , "status_code" ) and e .status_code == 409 ):
76+ erroString = (
77+ f"Role Assignment failed. Please manually assign the `Monitoring Data Reader` role\n "
78+ f"to the Azure Monitor Workspace ({ azure_monitor_workspace_resource_id } ) "
79+ f"for the Azure Managed Grafana\n System Assigned Managed Identity ({ servicePrincipalId } )"
80+ )
81+ print (erroString )
82+ except Exception as e :
83+ raise CLIError (e )
8084 # Setting up AMW Integration
81- targetGrafanaArmPayload = grafanaArmResponse .json ()
85+ targetGrafanaArmPayload = (
86+ grafanaArmResponse .as_dict ()
87+ if hasattr (grafanaArmResponse , "as_dict" )
88+ else grafanaArmResponse
89+ )
8290 if targetGrafanaArmPayload ["properties" ] is None :
8391 raise CLIError ("Invalid grafana payload to add AMW integration" )
8492 if "grafanaIntegrations" not in json .dumps (targetGrafanaArmPayload ):
@@ -89,17 +97,14 @@ def link_grafana_instance(cmd, raw_parameters, azure_monitor_workspace_resource_
8997 if amwIntegrations != [] and azure_monitor_workspace_resource_id in json .dumps (amwIntegrations ).lower ():
9098 return GrafanaLink .ALREADYPRESENT
9199 try :
92- grafanaURI = "{0}{1}?api-version={2}" .format (
93- cmd .cli_ctx .cloud .endpoints .resource_manager ,
94- grafana_resource_id ,
95- GRAFANA_API
96- )
97100 targetGrafanaArmPayload ["properties" ]["grafanaIntegrations" ]["azureMonitorWorkspaceIntegrations" ].append ({
98101 "azureMonitorWorkspaceResourceId" : azure_monitor_workspace_resource_id
99102 })
100- targetGrafanaArmPayload = json .dumps (targetGrafanaArmPayload )
101- headers = ['User-Agent=azuremonitormetrics.setup_amw_grafana_integration' , 'Content-Type=application/json' ]
102- send_raw_request (cmd .cli_ctx , "PUT" , grafanaURI , body = targetGrafanaArmPayload , headers = headers )
103+ resources .begin_create_or_update_by_id (
104+ grafana_resource_id ,
105+ GRAFANA_API ,
106+ targetGrafanaArmPayload
107+ )
103108 except CLIError as e :
104109 raise CLIError (e )
105110 return GrafanaLink .SUCCESS
0 commit comments