Exemplo n.º 1
0
        protected void AddAcrRoleAssignment(string acrName, string acrParameterName, AcsServicePrincipal acsServicePrincipal)
        {
            string acrResourceId = null;

            try
            {
                //Find Acr resourceId first
                var acrQuery   = new ODataQuery <GenericResourceFilter>($"$filter=resourceType eq 'Microsoft.ContainerRegistry/registries' and name eq '{acrName}'");
                var acrObjects = RmClient.Resources.List(acrQuery);
                acrResourceId = acrObjects.First().Id;
            }
            catch (Exception)
            {
                throw new AzPSArgumentException(
                          string.Format(Resources.CouldNotFindSpecifiedAcr, acrName),
                          acrParameterName,
                          string.Format(Resources.CouldNotFindSpecifiedAcr, "*"));
            }

            var            roleId         = GetRoleId("acrpull", acrResourceId);
            RoleAssignment roleAssignment = GetRoleAssignmentWithRoleDefinitionId(roleId);

            if (roleAssignment != null)
            {
                WriteWarning(string.Format(Resources.AcrRoleAssignmentIsAlreadyExist, acrResourceId));
                return;
            }
            var spObjectId = acsServicePrincipal.ObjectId;

            if (spObjectId == null)
            {
                try
                {
                    ODataQuery <MicrosoftGraphServicePrincipal> oDataQuery = new ODataQuery <MicrosoftGraphServicePrincipal>(sp => sp.AppId == acsServicePrincipal.SpId);
                    var servicePrincipal = GraphClient.FilterServicePrincipals(oDataQuery).First();
                    spObjectId = servicePrincipal.Id;
                }
                catch (Exception ex)
                {
                    throw new AzPSInvalidOperationException(
                              string.Format(Resources.CouldNotFindObjectIdForServicePrincipal, acsServicePrincipal.SpId),
                              ex,
                              string.Format(Resources.CouldNotFindObjectIdForServicePrincipal, "*"));
                }
            }
            var success = RetryAction(() =>
                                      AuthClient.RoleAssignments.Create(acrResourceId, Guid.NewGuid().ToString(), new RoleAssignmentCreateParameters()
            {
                Properties = new RoleAssignmentProperties(roleId, spObjectId)
            }), Resources.AddRoleAssignment);

            if (!success)
            {
                throw new AzPSInvalidOperationException(
                          Resources.CouldNotAddAcrRoleAssignment,
                          desensitizedMessage: Resources.CouldNotAddAcrRoleAssignment);
            }
        }