public async Task WhatIfAtSubscriptionScope_ResourceIdOnlyMode_ReturnsChangesWithResourceIdsOnly()
        {
            // Arrange.
            var deploymentWhatIf = new DeploymentWhatIf(
                new DeploymentWhatIfProperties(DeploymentMode.Incremental)
            {
                Template       = SubscriptionTemplate,
                WhatIfSettings = new DeploymentWhatIfSettings()
                {
                    ResultFormat = WhatIfResultFormat.ResourceIdOnly
                }
            }
                )
            {
                Location = "westus"
            };

            // Act.
            var rawResult = await DeploymentsOperations.StartWhatIfAtSubscriptionScopeAsync(NewDeploymentName(), deploymentWhatIf);

            var result = (await WaitForCompletionAsync(rawResult)).Value;

            // Assert.
            Assert.AreEqual("Succeeded", result.Status);
            Assert.NotNull(result.Changes);
            Assert.IsNotEmpty(result.Changes);
            foreach (var change in result.Changes)
            {
                Assert.NotNull(change.ResourceId);
                Assert.IsNotEmpty(change.ResourceId);
                Assert.True(change.ChangeType == ChangeType.Deploy || change.ChangeType == ChangeType.Create);
                Assert.Null(change.Before);
                Assert.Null(change.After);
                Assert.Null(change.Delta);
            }
        }
        public void WhatIfAtSubscriptionScope_ResourceIdOnlyMode_ReturnsChangesWithResourceIdsOnly()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Arrange.
                ResourceManagementClient client = this.GetResourceManagementClient(context);
                var deploymentWhatIf            = new DeploymentWhatIf
                {
                    Location   = "westus",
                    Properties = new DeploymentWhatIfProperties
                    {
                        Mode           = DeploymentMode.Incremental,
                        Template       = SubscriptionTemplate,
                        WhatIfSettings = new DeploymentWhatIfSettings(WhatIfResultFormat.ResourceIdOnly)
                    }
                };

                // Act.
                WhatIfOperationResult result = client.Deployments
                                               .WhatIfAtSubscriptionScope(NewDeploymentName(), deploymentWhatIf);

                // Assert.
                Assert.Equal("Succeeded", result.Status);
                Assert.NotNull(result.Changes);
                Assert.NotEmpty(result.Changes);
                result.Changes.ForEach(change =>
                {
                    Assert.NotNull(change.ResourceId);
                    Assert.NotEmpty(change.ResourceId);
                    Assert.True(change.ChangeType == ChangeType.Deploy || change.ChangeType == ChangeType.Create);
                    Assert.Null(change.Before);
                    Assert.Null(change.After);
                    Assert.Null(change.Delta);
                });
            }
        }
Example #3
0
        public void WhatIfAtSubscriptionScope_ModifyResources_ReturnsModifyChanges()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Arrange.
                ResourceManagementClient client = this.GetResourceManagementClient(context);

                var deployment = new Deployment
                {
                    Location   = "westus2",
                    Properties = new DeploymentProperties
                    {
                        Mode       = DeploymentMode.Incremental,
                        Template   = SubscriptionTemplate,
                        Parameters = JObject.Parse("{ 'storageAccountName': {'value': 'whatifnetsdktest1'}}"),
                    }
                };

                // Change "northeurope" to "westeurope".
                JObject newTemplate = JObject.Parse(SubscriptionTemplate);
                newTemplate["resources"][0]["properties"]["policyRule"]["if"]["equals"] = "westeurope";

                var deploymentWhatIf = new DeploymentWhatIf
                {
                    Location   = "westus2",
                    Properties = new DeploymentWhatIfProperties
                    {
                        Mode           = DeploymentMode.Incremental,
                        Template       = newTemplate,
                        Parameters     = JObject.Parse("{ 'storageAccountName': {'value': 'whatifnetsdktest1'}}"),
                        WhatIfSettings = new DeploymentWhatIfSettings(WhatIfResultFormat.FullResourcePayloads)
                    }
                };

                client.ResourceGroups.CreateOrUpdate("SDK-test", ResourceGroup);
                client.Deployments.CreateOrUpdateAtSubscriptionScope(NewDeploymentName(), deployment);

                // Act.
                WhatIfOperationResult result = client.Deployments
                                               .WhatIfAtSubscriptionScope(NewDeploymentName(), deploymentWhatIf);

                // Assert.
                Assert.Equal("Succeeded", result.Status);
                Assert.NotNull(result.Changes);
                Assert.NotEmpty(result.Changes);

                WhatIfChange policyChange = result.Changes.FirstOrDefault(change =>
                                                                          change.ResourceId.EndsWith("Microsoft.Authorization/policyDefinitions/policy2"));

                Assert.NotNull(policyChange);
                Assert.True(policyChange.ChangeType == ChangeType.Deploy ||
                            policyChange.ChangeType == ChangeType.Modify);
                Assert.NotNull(policyChange.Delta);
                Assert.NotEmpty(policyChange.Delta);

                WhatIfPropertyChange policyRuleChange = policyChange.Delta
                                                        .FirstOrDefault(propertyChange => propertyChange.Path.Equals("properties.policyRule.if.equals"));

                Assert.NotNull(policyRuleChange);
                Assert.Equal(PropertyChangeType.Modify, policyRuleChange.PropertyChangeType);
                Assert.Equal("northeurope", policyRuleChange.Before);
                Assert.Equal("westeurope", policyRuleChange.After);
            }
        }
Example #4
0
        public void WhatIf_ModifyResources_ReturnsModifyChanges()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Arrange.
                ResourceManagementClient client = this.GetResourceManagementClient(context);

                var deployment = new Deployment
                {
                    Properties = new DeploymentProperties
                    {
                        Mode       = DeploymentMode.Incremental,
                        Template   = ResourceGroupTemplate,
                        Parameters = ResourceGroupTemplateParameters,
                    }
                };

                // Modify account type: Standard_LRS => Standard_GRS.
                JObject newTemplate = JObject.Parse(ResourceGroupTemplate);
                newTemplate["resources"][0]["properties"]["accountType"] = "Standard_GRS";

                var deploymentWhatIf = new DeploymentWhatIf
                {
                    Properties = new DeploymentWhatIfProperties
                    {
                        Mode           = DeploymentMode.Incremental,
                        Template       = newTemplate,
                        Parameters     = ResourceGroupTemplateParameters,
                        WhatIfSettings = new DeploymentWhatIfSettings(WhatIfResultFormat.FullResourcePayloads)
                    }
                };

                string resourceGroupName = NewResourceGroupName();

                client.ResourceGroups.CreateOrUpdate(resourceGroupName, ResourceGroup);
                client.Deployments.CreateOrUpdate(resourceGroupName, NewDeploymentName(), deployment);

                // Act.
                WhatIfOperationResult result = client.Deployments
                                               .WhatIf(resourceGroupName, NewDeploymentName(), deploymentWhatIf);

                // Assert.
                Assert.Equal("Succeeded", result.Status);
                Assert.NotNull(result.Changes);
                Assert.NotEmpty(result.Changes);

                WhatIfChange storageAccountChange = result.Changes.FirstOrDefault(change =>
                                                                                  change.ResourceId.EndsWith("Microsoft.Storage/storageAccounts/tianotest102"));

                Assert.NotNull(storageAccountChange);
                Assert.Equal(ChangeType.Modify, storageAccountChange.ChangeType);

                Assert.NotNull(storageAccountChange.Delta);
                Assert.NotEmpty(storageAccountChange.Delta);

                WhatIfPropertyChange accountTypeChange = storageAccountChange.Delta
                                                         .FirstOrDefault(propertyChange => propertyChange.Path.Equals("properties.accountType"));

                Assert.NotNull(accountTypeChange);
                Assert.Equal("Standard_LRS", accountTypeChange.Before);
                Assert.Equal("Standard_GRS", accountTypeChange.After);
            }
        }
        public void WhatIf_ReceivingResponse_DeserializesResult()
        {
            // Arrange.
            var deploymentWhatIf = new DeploymentWhatIf(new DeploymentWhatIfProperties());
            var response         = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'status': 'Succeeded',
                    'properties': {
                        'changes': [
                            {
                                'resourceId': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                'changeType': 'Modify',
                                'before': {
                                    'apiVersion': '2018-11-30',
                                    'id': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                    'type': 'Microsoft.ManagedIdentity/userAssignedIdentities',
                                    'name': 'myExistingIdentity',
                                    'location': 'westus2'
                                },
                                'after': {
                                    'apiVersion': '2018-11-30',
                                    'id': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                    'type': 'Microsoft.ManagedIdentity/userAssignedIdentities',
                                    'name': 'myExistingIdentity',
                                    'location': 'westus2',
                                    'tags': {
                                        'myNewTag': 'my tag value'
                                    }
                                },
                                'delta': [
                                    {
                                        'path': 'tags.myNewTag',
                                        'propertyChangeType': 'Create',
                                        'after': 'my tag value'
                                    }
                                ]
                            }
                        ]
                    }
                }")
            };
            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (ResourceManagementClient client = CreateResourceManagementClient(handler))
            {
                // Act.
                WhatIfOperationResult result = client.Deployments.WhatIf("test-rg", "test-deploy", deploymentWhatIf);

                // Assert.
                Assert.Equal("Succeeded", result.Status);
                Assert.NotNull(result.Changes);
                Assert.Equal(1, result.Changes.Count);

                WhatIfChange change = result.Changes[0];
                Assert.Equal(ChangeType.Modify, change.ChangeType);

                Assert.NotNull(change.Before);
                Assert.Equal("myExistingIdentity", JToken.FromObject(change.Before)["name"]);

                Assert.NotNull(change.After);
                Assert.Equal("myExistingIdentity", JToken.FromObject(change.After)["name"]);

                Assert.NotNull(change.Delta);
                Assert.Equal(1, change.Delta.Count);
                Assert.Equal("tags.myNewTag", change.Delta[0].Path);
                Assert.Equal(PropertyChangeType.Create, change.Delta[0].PropertyChangeType);
                Assert.Equal("my tag value", change.Delta[0].After);
            }
        }
Example #6
0
        public static string SerializeDeploymentWhatIf(DeploymentWhatIf deploymentWhatIf, JsonSerializerSettings settings)
        {
            CheckSerializationForDeploymentProperties(deploymentWhatIf.Properties);

            return(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(deploymentWhatIf, settings));
        }
Example #7
0
        public virtual ArmOperation <WhatIfOperationResult> WhatIf(bool waitForCompletion, DeploymentWhatIf parameters, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(parameters, nameof(parameters));

            using var scope = _deploymentClientDiagnostics.CreateScope("Deployment.WhatIf");
            scope.Start();
            try
            {
                if (Id.Parent.ResourceType == Tenant.ResourceType)
                {
                    var response  = _deploymentRestClient.WhatIfAtTenantScope(Id.Name, parameters, cancellationToken);
                    var operation = new ResourcesArmOperation <WhatIfOperationResult>(new WhatIfOperationResultOperationSource(), _deploymentClientDiagnostics, Pipeline, _deploymentRestClient.CreateWhatIfAtTenantScopeRequest(Id.Name, parameters).Request, response, OperationFinalStateVia.Location);
                    if (waitForCompletion)
                    {
                        operation.WaitForCompletion(cancellationToken);
                    }
                    return(operation);
                }
                else if (Id.Parent.ResourceType == ManagementGroup.ResourceType)
                {
                    var response  = _deploymentRestClient.WhatIfAtManagementGroupScope(Id.Parent.Name, Id.Name, parameters, cancellationToken);
                    var operation = new ResourcesArmOperation <WhatIfOperationResult>(new WhatIfOperationResultOperationSource(), _deploymentClientDiagnostics, Pipeline, _deploymentRestClient.CreateWhatIfAtManagementGroupScopeRequest(Id.Parent.Name, Id.Name, parameters).Request, response, OperationFinalStateVia.Location);
                    if (waitForCompletion)
                    {
                        operation.WaitForCompletion(cancellationToken);
                    }
                    return(operation);
                }
                else if (Id.Parent.ResourceType == Subscription.ResourceType)
                {
                    var response  = _deploymentRestClient.WhatIfAtSubscriptionScope(Id.SubscriptionId, Id.Name, parameters, cancellationToken);
                    var operation = new ResourcesArmOperation <WhatIfOperationResult>(new WhatIfOperationResultOperationSource(), _deploymentClientDiagnostics, Pipeline, _deploymentRestClient.CreateWhatIfAtSubscriptionScopeRequest(Id.SubscriptionId, Id.Name, parameters).Request, response, OperationFinalStateVia.Location);
                    if (waitForCompletion)
                    {
                        operation.WaitForCompletion(cancellationToken);
                    }
                    return(operation);
                }
                else if (Id.Parent.ResourceType == ResourceGroup.ResourceType)
                {
                    var response  = _deploymentRestClient.WhatIf(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, parameters, cancellationToken);
                    var operation = new ResourcesArmOperation <WhatIfOperationResult>(new WhatIfOperationResultOperationSource(), _deploymentClientDiagnostics, Pipeline, _deploymentRestClient.CreateWhatIfRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, parameters).Request, response, OperationFinalStateVia.Location);
                    if (waitForCompletion)
                    {
                        operation.WaitForCompletion(cancellationToken);
                    }
                    return(operation);
                }
                else
                {
                    throw new InvalidOperationException($"{Id.Parent.ResourceType} is not supported here");
                }
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
        public async Task WhatIf_ModifyResources_ReturnsModifyChanges()
        {
            // Arrange.
            JsonElement jsonParameter = JsonSerializer.Deserialize <JsonElement>(ResourceGroupTemplateParameters);

            if (!jsonParameter.TryGetProperty("parameters", out JsonElement parameter))
            {
                parameter = jsonParameter;
            }

            var deployment = new Deployment(new DeploymentProperties(DeploymentMode.Incremental)
            {
                Template       = ResourceGroupTemplate,
                ParametersJson = parameter
            });

            // Modify account type: Standard_LRS => Standard_GRS.
            var deploymentWhatIf = new DeploymentWhatIf(
                new DeploymentWhatIfProperties(DeploymentMode.Incremental)
            {
                Template       = ResourceGroupTemplateGRS,
                ParametersJson = parameter,
                WhatIfSettings = new DeploymentWhatIfSettings()
                {
                    ResultFormat = WhatIfResultFormat.FullResourcePayloads
                }
            }
                );

            string resourceGroupName = NewResourceGroupName();

            var resourcegroup = (await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, ResourceGroup)).Value;
            var deploy        = await DeploymentsOperations.StartCreateOrUpdateAsync(resourceGroupName, NewDeploymentName(), deployment);

            await WaitForCompletionAsync(deploy);

            // Act.
            var rawResult = await DeploymentsOperations.StartWhatIfAsync(resourceGroupName, NewDeploymentName(), deploymentWhatIf);

            var result = (await WaitForCompletionAsync(rawResult)).Value;

            // Assert.
            Assert.AreEqual("Succeeded", result.Status);
            Assert.NotNull(result.Changes);
            Assert.IsNotEmpty(result.Changes);

            WhatIfChange storageAccountChange = result.Changes.FirstOrDefault(change =>
                                                                              change.ResourceId.EndsWith("Microsoft.Storage/storageAccounts/ramokaSATestAnother1"));

            Assert.NotNull(storageAccountChange);
            Assert.AreEqual(ChangeType.Modify, storageAccountChange.ChangeType);

            Assert.NotNull(storageAccountChange.Delta);
            Assert.IsNotEmpty(storageAccountChange.Delta);

            WhatIfPropertyChange accountTypeChange = storageAccountChange.Delta
                                                     .FirstOrDefault(propertyChange => propertyChange.Path.Equals("properties.accountType"));

            Assert.NotNull(accountTypeChange);
            Assert.AreEqual("Standard_LRS", accountTypeChange.Before);
            Assert.AreEqual("Standard_GRS", accountTypeChange.After);
        }
        public async Task WhatIfAtSubscriptionScope_SendingRequestWithStrings_SerializesPayload()
        {
            // Arrange.
            string[] divideCases =
            {
                @"{
                    '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#',
                    'contentVersion': '1.0.0.0',
                    'parameters': {
                        'roleDefName': {
                            'value': 'myCustomRole'
                        }
                    }
                }".Replace("'", "\""),
                @"{
                    'roleDefName': {
                        'value': 'myCustomRole'
                    }
                }".Replace("'", "\"")
            };
            foreach (string item in divideCases)
            {
                string templateContent = @"{
                    '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#',
                    'contentVersion': '1.0.0.0',
                    'parameters': {
                        'roleDefName': {
		                    'type': 'string'
	                    }
                    },
                    'resources': [
                    ],
                    'outputs': {}
                }".Replace("'", "\"");
                var    mockResponse    = new MockResponse((int)HttpStatusCode.OK);

                JsonElement jsonParameter = JsonSerializer.Deserialize <JsonElement>(item);
                if (!jsonParameter.TryGetProperty("parameters", out JsonElement parameter))
                {
                    parameter = jsonParameter;
                }

                var deploymentWhatIf = new DeploymentWhatIf(
                    new DeploymentWhatIfProperties(DeploymentMode.Incremental)
                {
                    Template       = templateContent,
                    ParametersJson = parameter
                })
                {
                    Location = "westus"
                };

                var mockTransport = new MockTransport(mockResponse);
                var client        = GetResourceManagementClient(mockTransport);

                // Act.
                await client.Deployments.StartWhatIfAtSubscriptionScopeAsync("test-subscription-deploy", deploymentWhatIf);

                // Assert.
                var    request = mockTransport.Requests[0];
                Stream stream  = new MemoryStream();
                await request.Content.WriteToAsync(stream, default);

                stream.Position = 0;
                var resquestContent = new StreamReader(stream).ReadToEnd();
                var resultJson      = JsonDocument.Parse(resquestContent).RootElement;
                Assert.AreEqual("Incremental", resultJson.GetProperty("properties").GetProperty("mode").GetString());
                Assert.AreEqual("1.0.0.0", resultJson.GetProperty("properties").GetProperty("template").GetProperty("contentVersion").GetString());
                Assert.AreEqual("myCustomRole", resultJson.GetProperty("properties").GetProperty("parameters").GetProperty("roleDefName").GetProperty("value").GetString());
            }
        }
        public async Task WhatIf_ReceivingResponse_DeserializesResult()
        {
            // Arrange.
            var deploymentWhatIf = new DeploymentWhatIf(new DeploymentWhatIfProperties(DeploymentMode.Incremental));
            var content          = @"{
                    'status': 'Succeeded',
                    'properties': {
                        'changes': [
                            {
                                'resourceId': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                'changeType': 'Modify',
                                'before': {
                                    'apiVersion': '2018-11-30',
                                    'id': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                    'type': 'Microsoft.ManagedIdentity/userAssignedIdentities',
                                    'name': 'myExistingIdentity',
                                    'location': 'westus2'
                                },
                                'after': {
                                    'apiVersion': '2018-11-30',
                                    'id': '/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myExistingIdentity',
                                    'type': 'Microsoft.ManagedIdentity/userAssignedIdentities',
                                    'name': 'myExistingIdentity',
                                    'location': 'westus2',
                                    'tags': {
                                        'myNewTag': 'my tag value'
                                    }
                                },
                                'delta': [
                                    {
                                        'path': 'tags.myNewTag',
                                        'propertyChangeType': 'Create',
                                        'after': 'my tag value'
                                    }
                                ]
                            }
                        ]
                    }
                }".Replace("'", "\"");

            var mockResponse = new MockResponse((int)HttpStatusCode.OK);

            mockResponse.SetContent(content);
            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            // Act.
            var raw = await client.Deployments.StartWhatIfAsync("test-rg", "test-deploy", deploymentWhatIf);

            var result = (await WaitForCompletionAsync(raw)).Value;

            // Assert.
            Assert.AreEqual("Succeeded", result.Status);
            Assert.NotNull(result.Changes);
            Assert.AreEqual(1, result.Changes.Count);

            WhatIfChange change = result.Changes[0];

            Assert.AreEqual(ChangeType.Modify, change.ChangeType);

            Assert.NotNull(change.Before);
            Assert.AreEqual("myExistingIdentity", JsonDocument.Parse(JsonSerializer.Serialize(change.Before)).RootElement.GetProperty("name").GetString());

            Assert.NotNull(change.After);
            Assert.AreEqual("myExistingIdentity", JsonDocument.Parse(JsonSerializer.Serialize(change.After)).RootElement.GetProperty("name").GetString());

            Assert.NotNull(change.Delta);
            Assert.AreEqual(1, change.Delta.Count);
            Assert.AreEqual("tags.myNewTag", change.Delta[0].Path);
            Assert.AreEqual(PropertyChangeType.Create, change.Delta[0].PropertyChangeType);
            Assert.AreEqual("my tag value", change.Delta[0].After);
        }