Пример #1
0
        public override void ExecuteCmdlet()
        {
            PsDeploymentScriptLog deploymentScriptLog;

            try
            {
                switch (ParameterSetName)
                {
                case GetDeploymentScriptLogByName:
                    deploymentScriptLog =
                        DeploymentScriptsSdkClient.GetDeploymentScriptLog(Name, ResourceGroupName);
                    break;

                case GetDeploymentScriptLogByResourceId:
                    deploymentScriptLog = DeploymentScriptsSdkClient.GetDeploymentScriptLog(
                        ResourceIdUtility.GetResourceName(this.DeploymentScriptResourceId),
                        ResourceIdUtility.GetResourceGroupName(this.DeploymentScriptResourceId));
                    break;

                case GetDeploymentScriptLogByInputObject:
                    deploymentScriptLog = DeploymentScriptsSdkClient.GetDeploymentScriptLog(DeploymentScriptInputObject.Name,
                                                                                            ResourceIdUtility.GetResourceGroupName(DeploymentScriptInputObject.Id));
                    break;

                default:
                    throw new PSInvalidOperationException();
                }

                WriteObject(deploymentScriptLog);
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
Пример #2
0
        private List <DeploymentOperation> GetNewOperations(List <DeploymentOperation> old, IList <DeploymentOperation> current)
        {
            List <DeploymentOperation> newOperations = new List <DeploymentOperation>();

            foreach (DeploymentOperation operation in current)
            {
                DeploymentOperation operationWithSameIdAndProvisioningState = old.Find(o => o.OperationId.Equals(operation.OperationId) && o.Properties.ProvisioningState.Equals(operation.Properties.ProvisioningState));
                if (operationWithSameIdAndProvisioningState == null)
                {
                    newOperations.Add(operation);
                }

                //If nested deployment, get the operations under those deployments as well
                if (operation.Properties.TargetResource != null && operation.Properties.TargetResource.ResourceType.Equals(Constants.MicrosoftResourcesDeploymentType, StringComparison.OrdinalIgnoreCase))
                {
                    HttpStatusCode statusCode;
                    Enum.TryParse <HttpStatusCode>(operation.Properties.StatusCode, out statusCode);
                    if (!statusCode.IsClientFailureRequest())
                    {
                        List <DeploymentOperation>     newNestedOperations = new List <DeploymentOperation>();
                        DeploymentOperationsListResult result;

                        result = ResourceManagementClient.DeploymentOperations.List(
                            resourceGroupName: ResourceIdUtility.GetResourceGroupName(operation.Properties.TargetResource.Id),
                            deploymentName: operation.Properties.TargetResource.ResourceName,
                            parameters: null);

                        newNestedOperations = GetNewOperations(operations, result.Operations);
                        newOperations.AddRange(newNestedOperations);
                    }
                }
            }

            return(newOperations);
        }
        public override void ExecuteCmdlet()
        {
            try
            {
                switch (ParameterSetName)
                {
                case GetDeploymentScriptByName:
                    WriteObject(DeploymentScriptsSdkClient.GetDeploymentScript(Name, ResourceGroupName));
                    break;

                case GetDeploymentScriptByResourceId:
                    WriteObject(DeploymentScriptsSdkClient.GetDeploymentScript(ResourceIdUtility.GetResourceName(this.Id),
                                                                               ResourceIdUtility.GetResourceGroupName(this.Id)));
                    break;

                case ListDeploymentScript:
                    WriteObject(!string.IsNullOrEmpty(ResourceGroupName)
                            ? DeploymentScriptsSdkClient.ListDeploymentScriptsByResourceGroup(ResourceGroupName)
                            : DeploymentScriptsSdkClient.ListDeploymentScriptsBySubscription());
                    break;

                default:
                    throw new PSInvalidOperationException();
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
        public override void ExecuteCmdlet()
        {
            PsDeploymentScriptLog deploymentScriptLog;

            try
            {
                switch (ParameterSetName)
                {
                case SaveDeploymentScriptLogByName:
                    deploymentScriptLog =
                        DeploymentScriptsSdkClient.GetDeploymentScriptLog(Name, ResourceGroupName);
                    break;

                case SaveDeploymentScriptLogByResourceId:
                    deploymentScriptLog = DeploymentScriptsSdkClient.GetDeploymentScriptLog(
                        ResourceIdUtility.GetResourceName(this.DeploymentScriptResourceId),
                        ResourceIdUtility.GetResourceGroupName(this.DeploymentScriptResourceId));
                    break;

                case SaveDeploymentScriptLogByInputObject:
                    deploymentScriptLog = DeploymentScriptsSdkClient.GetDeploymentScriptLog(
                        DeploymentScriptInputObject.Name,
                        ResourceIdUtility.GetResourceGroupName(DeploymentScriptInputObject.Id));
                    break;

                default:
                    throw new PSInvalidOperationException();
                }

                if (!string.IsNullOrEmpty(OutputPath) && !string.IsNullOrEmpty(deploymentScriptLog?.Log))
                {
                    var outputPathWithFileName = Path.Combine(GetValidatedFolderPath(OutputPath),
                                                              $"{deploymentScriptLog.DeploymentScriptName}.txt");

                    // if a file with the same name exists and -Force is not provided, let's ask if we can replace the file.
                    this.ConfirmAction(
                        this.Force || !AzureSession.Instance.DataStore.FileExists(outputPathWithFileName),
                        string.Format(
                            Properties.Resources.DeploymentScriptLogFileExists, Name, OutputPath),
                        Properties.Resources.DeploymentScriptShouldProcessString,
                        OutputPath,
                        () =>
                    {
                        AzureSession.Instance.DataStore.WriteFile(outputPathWithFileName,
                                                                  deploymentScriptLog.Log);

                        WriteObject(new PsDeploymentScriptLogPath()
                        {
                            Path = outputPathWithFileName
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
        public override void ExecuteCmdlet()
        {
            FilterResourceGroupDeploymentOptions options = new FilterResourceGroupDeploymentOptions()
            {
                ResourceGroupName = ResourceGroupName ?? ResourceIdUtility.GetResourceGroupName(Id),
                DeploymentName    = Name ?? (string.IsNullOrEmpty(Id) ? null : ResourceIdUtility.GetResourceName(Id))
            };

            WriteObject(ResourcesClient.FilterResourceGroupDeployments(options), true);
        }
Пример #6
0
        protected override void ProcessRecord()
        {
            FilterResourceGroupDeploymentOptions options = new FilterResourceGroupDeploymentOptions()
            {
                ResourceGroupName = ResourceGroupName ?? ResourceIdUtility.GetResourceGroupName(Id),
                DeploymentName    = Name ?? (string.IsNullOrEmpty(Id) ? null : ResourceIdUtility.GetResourceName(Id))
            };

            WriteObject(ResourcesClient.FilterResourceGroupDeployments(options), true);
        }
Пример #7
0
        public override void ExecuteCmdlet()
        {
            WriteWarning("The output object type of this cmdlet will be modified in a future release.");
            FilterResourceGroupDeploymentOptions options = new FilterResourceGroupDeploymentOptions()
            {
                ResourceGroupName = ResourceGroupName ?? ResourceIdUtility.GetResourceGroupName(Id),
                DeploymentName    = Name ?? (string.IsNullOrEmpty(Id) ? null : ResourceIdUtility.GetResourceName(Id))
            };

            WriteObject(ResourcesClient.FilterResourceGroupDeployments(options), true);
        }
Пример #8
0
        public PsPolicyExemption(JToken input)
        {
            var resource = input.ToResource();

            Name              = resource.Name;
            Properties        = new PsPolicyExemptionProperties(resource.Properties);
            ResourceId        = resource.Id;
            ResourceName      = resource.Name;
            ResourceGroupName = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id);
            ResourceType      = resource.Type;
            SubscriptionId    = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id);
        }
Пример #9
0
        public override void ExecuteCmdlet()
        {
            if (string.IsNullOrEmpty(ResourceGroupName) && string.IsNullOrEmpty(Name))
            {
                ResourceGroupName = ResourceIdUtility.GetResourceGroupName(Id);
                Name = ResourceIdUtility.GetResourceName(Id);
            }
            ConfirmAction(
                ProjectResources.CancelResourceGroupDeploymentMessage,
                ResourceGroupName,
                () => ResourceManagerSdkClient.CancelDeployment(ResourceGroupName, Name));

            WriteObject(true);
        }
Пример #10
0
        public PsPolicyAssignment(JToken input)
        {
            var resource = input.ToResource();

            Identity           = resource.Identity?.ToJToken().ToPsObject();
            Location           = resource.Location;
            Name               = resource.Name;
            PolicyAssignmentId = resource.Id;
            Properties         = new PsPolicyAssignmentProperties(resource.Properties);
            ResourceId         = resource.Id;
            ResourceName       = resource.Name;
            ResourceGroupName  = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id);
            ResourceType       = resource.Type;
            Sku            = resource.Sku?.ToJToken().ToPsObject();
            SubscriptionId = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id);
        }
        protected override void ProcessRecord()
        {
            if (string.IsNullOrEmpty(ResourceGroupName) && string.IsNullOrEmpty(Name))
            {
                ResourceGroupName = ResourceIdUtility.GetResourceGroupName(Id);
                Name = ResourceIdUtility.GetResourceName(Id);
            }
            ConfirmAction(
                Force.IsPresent,
                string.Format(ProjectResources.DeleteResourceGroupDeployment, Name),
                ProjectResources.DeleteResourceGroupDeploymentMessage,
                ResourceGroupName,
                () => ResourcesClient.DeleteDeployment(ResourceGroupName, Name));

            WriteObject(true);
        }
        public override void ExecuteCmdlet()
        {
            try
            {
                switch (ParameterSetName)
                {
                case GetTemplateSpecByNameParameterSet:
                    WriteObject(
                        TemplateSpecsSdkClient.GetTemplateSpec(Name, ResourceGroupName, Version)
                        );
                    break;

                case GetTemplateSpecByIdParameterSet:
                    WriteObject(
                        TemplateSpecsSdkClient.GetTemplateSpec(
                            ResourceIdUtility.GetResourceName(this.ResourceId),
                            ResourceIdUtility.GetResourceGroupName(this.ResourceId),
                            Version
                            )
                        );
                    break;

                case ListTemplateSpecsParameterSet:
                    var templateSpecs = !string.IsNullOrEmpty(ResourceGroupName)
                            ? TemplateSpecsSdkClient.ListTemplateSpecsByResourceGroup(ResourceGroupName)
                            : TemplateSpecsSdkClient.ListTemplateSpecsBySubscription();

                    var templateSpecListItems = templateSpecs
                                                .Select(ts => PSTemplateSpecListItem.FromTemplateSpec(ts))
                                                .GroupBy(ts => ts.Id).Select(g => g.First()) // Required due to current backend bug returning duplicates
                                                .OrderBy(ts => ts.ResourceGroupName)
                                                .ThenBy(ts => ts.Name)
                                                .Distinct()
                                                .ToList();

                    WriteObject(templateSpecListItems);
                    break;

                default:
                    throw new PSInvalidOperationException();
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
Пример #13
0
        private List <DeploymentOperation> GetNewOperations(List <DeploymentOperation> old, IPage <DeploymentOperation> current)
        {
            List <DeploymentOperation> newOperations = new List <DeploymentOperation>();

            foreach (DeploymentOperation operation in current)
            {
                DeploymentOperation operationWithSameIdAndProvisioningState = old.Find(o => o.OperationId.Equals(operation.OperationId) && o.Properties.ProvisioningState.Equals(operation.Properties.ProvisioningState));
                if (operationWithSameIdAndProvisioningState == null)
                {
                    newOperations.Add(operation);
                }

                //If nested deployment, get the operations under those deployments as well
                if (operation.Properties.TargetResource != null && operation.Properties.TargetResource.ResourceType.Equals(Constants.MicrosoftResourcesDeploymentType, StringComparison.OrdinalIgnoreCase))
                {
                    HttpStatusCode statusCode;
                    Enum.TryParse <HttpStatusCode>(operation.Properties.StatusCode, out statusCode);
                    if (!statusCode.IsClientFailureRequest())
                    {
                        var resourceGroupName = ResourceIdUtility.GetResourceGroupName(operation.Properties.TargetResource.Id);
                        var deploymentName    = operation.Properties.TargetResource.ResourceName;

                        if (this.CheckDeploymentExistence(resourceGroupName, deploymentName) == true)
                        {
                            List <DeploymentOperation> newNestedOperations = new List <DeploymentOperation>();

                            var result = this.ListDeploymentOperations(resourceGroupName, deploymentName);

                            newNestedOperations = GetNewOperations(operations, result);

                            foreach (DeploymentOperation op in newNestedOperations)
                            {
                                DeploymentOperation nestedOperationWithSameIdAndProvisioningState = newOperations.Find(o => o.OperationId.Equals(op.OperationId) && o.Properties.ProvisioningState.Equals(op.Properties.ProvisioningState));

                                if (nestedOperationWithSameIdAndProvisioningState == null)
                                {
                                    newOperations.Add(op);
                                }
                            }
                        }
                    }
                }
            }

            return(newOperations);
        }
        public override void ExecuteCmdlet()
        {
            try
            {
                string scriptName = "";

                switch (ParameterSetName)
                {
                    case RemoveDeploymentScriptByName:
                        scriptName = Name;
                        if (ShouldProcess(scriptName, "Remove Deployment Script"))
                        {
                            DeploymentScriptsSdkClient.DeleteDeploymentScript(scriptName, ResourceGroupName);
                        }
                        break;
                    case RemoveDeploymentScriptByResourceId:
                        scriptName = ResourceIdUtility.GetResourceName(this.Id);
                        if (ShouldProcess(scriptName, "Remove Deployment Script"))
                        {
                            DeploymentScriptsSdkClient.DeleteDeploymentScript(scriptName,
                                ResourceIdUtility.GetResourceGroupName(this.Id));
                        }
                        break;
                    case RemoveDeploymentScriptByInputObject:
                        scriptName = InputObject.Name;
                        if (ShouldProcess(scriptName, "Remove Deployment Script"))
                        {
                            DeploymentScriptsSdkClient.DeleteDeploymentScript(scriptName, 
                                ResourceIdUtility.GetResourceGroupName(InputObject.Id));
                        }
                        break;
                    default:
                        throw new PSInvalidOperationException();
                }

                if (PassThru.IsPresent)
                {
                    WriteObject(true);
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
Пример #15
0
        public PSResource(Resource <JToken> resource)
        {
            this.Name                  = resource.Name;
            this.ResourceName          = resource.Name;
            this.ResourceId            = resource.Id;
            this.Id                    = resource.Id;
            this.Type                  = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceType(resource.Id);
            this.ResourceType          = Type;
            this.ExtensionResourceName = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceName(resource.Id);
            this.ExtensionResourceType = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceType(resource.Id);
            this.Kind                  = resource.Kind;
            this.ResourceGroupName     = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id);
            this.Location              = resource.Location;
            this.SubscriptionId        = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id);
            this.Tags                  = TagsHelper.GetTagsDictionary(TagsHelper.GetTagsHashtable(resource.Tags));
            this.Properties            = resource.Properties == null ? null : resource.Properties.ToPsObject();
            this.CreatedTime           = resource.CreatedTime;
            this.ChangedTime           = resource.ChangedTime;
            this.ETag                  = resource.ETag;
            this.Plan                  = resource.Plan == null ? null : new Plan
            {
                Name          = resource.Plan.Name,
                Publisher     = resource.Plan.Publisher,
                Product       = resource.Plan.Product,
                PromotionCode = resource.Plan.PromotionCode,
                Version       = resource.Plan.Version
            };
            this.Sku = resource.Sku == null ? null : new Sku
            {
                Name     = resource.Sku.Name,
                Tier     = resource.Sku.Tier,
                Size     = resource.Sku.Size,
                Family   = resource.Sku.Family,
                Capacity = resource.Sku.Capacity
            };

            if (resource.Identity != null)
            {
                this.Identity = new Identity(resource.Identity.PrincipalId, resource.Identity.TenantId);
                if (Enum.TryParse(resource.Identity.Type, out Management.ResourceManager.Models.ResourceIdentityType type))
                {
                    this.Identity.Type = type;
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Converts a <see cref="Resource{JToken}"/> object into a <see cref="PSObject"/> object.
        /// </summary>
        /// <param name="resource">The <see cref="Resource{JToken}"/> object.</param>
        internal static PSObject ToPsObject(this Resource <JToken> resource)
        {
            var resourceType = string.IsNullOrEmpty(resource.Id)
                ? null
                : ResourceIdUtility.GetResourceType(resource.Id);

            var extensionResourceType = string.IsNullOrEmpty(resource.Id)
                ? null
                : ResourceIdUtility.GetExtensionResourceType(resource.Id);

            var objectDefinition = new Dictionary <string, object>
            {
                { "Name", resource.Name },
                { "ResourceId", string.IsNullOrEmpty(resource.Id) ? null : resource.Id },
                { "ResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceName(resource.Id) },
                { "ResourceType", resourceType },
                { "ExtensionResourceName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceName(resource.Id) },
                { "ExtensionResourceType", extensionResourceType },
                { "Kind", resource.Kind },
                { "ResourceGroupName", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id) },
                { "Location", resource.Location },
                { "SubscriptionId", string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id) },
                { "Tags", TagsHelper.GetTagsHashtable(resource.Tags) },
                { "Plan", resource.Plan.ToJToken().ToPsObject() },
                { "Properties", ResourceExtensions.GetProperties(resource) },
                { "CreatedTime", resource.CreatedTime },
                { "ChangedTime", resource.ChangedTime },
                { "ETag", resource.ETag },
                { "Sku", resource.Sku.ToJToken().ToPsObject() },
                { "Zones", resource.Zones },
            };

            var resourceTypeName = resourceType == null && extensionResourceType == null
                ? null
                : (resourceType + extensionResourceType).Replace('/', '.');

            var psObject =
                PowerShellUtilities.ConstructPSObject(
                    resourceTypeName,
                    objectDefinition.Where(kvp => kvp.Value != null).SelectManyArray(kvp => new[] { kvp.Key, kvp.Value }));

            psObject.TypeNames.Add(Constants.MicrosoftAzureResource);
            return(psObject);
        }
        protected override void ProcessRecord()
        {
            FilterResourceGroupDeploymentOptions options = new FilterResourceGroupDeploymentOptions()
            {
                ResourceGroupName  = ResourceGroupName ?? ResourceIdUtility.GetResourceGroupName(Id),
                DeploymentName     = Name ?? (string.IsNullOrEmpty(Id) ? null : ResourceIdUtility.GetResourceName(Id)),
                ProvisioningStates = string.IsNullOrEmpty(ProvisioningState) ? new List <string>() :
                                     new List <string>()
                {
                    ProvisioningState
                }
            };

            if (!string.IsNullOrEmpty(ProvisioningState))
            {
                WriteWarning("The ProvisioningState parameter is being deprecated and will be removed in a future release.");
            }
            WriteObject(ResourcesClient.FilterResourceGroupDeployments(options), true);
        }
        protected override void ProcessRecord()
        {
            if (string.IsNullOrEmpty(ResourceGroupName) && string.IsNullOrEmpty(Name))
            {
                ResourceGroupName = ResourceIdUtility.GetResourceGroupName(Id);
                Name = ResourceIdUtility.GetResourceName(Id);
            }
            ConfirmAction(
                Force.IsPresent,
                string.Format(ProjectResources.CancelResourceGroupDeployment, ResourceGroupName),
                ProjectResources.CancelResourceGroupDeploymentMessage,
                ResourceGroupName,
                () => ResourcesClient.CancelDeployment(ResourceGroupName, Name));

            if (PassThru)
            {
                WriteWarning("The output object of this cmdlet will be modified in a future release.");
                WriteObject(true);
            }
        }
        protected override void ProcessRecord()
        {
            if (string.IsNullOrEmpty(ResourceGroupName) && string.IsNullOrEmpty(Name))
            {
                ResourceGroupName = ResourceIdUtility.GetResourceGroupName(Id);
                Name = ResourceIdUtility.GetResourceName(Id);
            }
            ConfirmAction(
                Force.IsPresent,
                string.Format(ProjectResources.DeleteResourceGroupDeployment, Name),
                ProjectResources.DeleteResourceGroupDeploymentMessage,
                ResourceGroupName,
                () => ResourcesClient.DeleteDeployment(ResourceGroupName, Name));

            if (PassThru)
            {
                WriteWarning("The PassThru switch parameter is being deprecated and will be removed in a future release.");
                WriteObject(true);
            }
        }
        public override void ExecuteCmdlet()
        {
            PsDeploymentScriptLog deploymentScriptLog;
            int    tailParam  = this.IsParameterBound(c => c.Tail) ? Tail : 0;
            string scriptName = "";

            try
            {
                switch (ParameterSetName)
                {
                case SaveDeploymentScriptLogByName:
                    scriptName          = Name;
                    deploymentScriptLog =
                        DeploymentScriptsSdkClient.GetDeploymentScriptLog(scriptName, ResourceGroupName, tailParam);
                    break;

                case SaveDeploymentScriptLogByResourceId:
                    scriptName          = ResourceIdUtility.GetResourceName(this.DeploymentScriptResourceId);
                    deploymentScriptLog = DeploymentScriptsSdkClient.GetDeploymentScriptLog(scriptName,
                                                                                            ResourceIdUtility.GetResourceGroupName(this.DeploymentScriptResourceId),
                                                                                            tailParam);
                    break;

                case SaveDeploymentScriptLogByInputObject:
                    scriptName          = DeploymentScriptObject.Name;
                    deploymentScriptLog = DeploymentScriptsSdkClient.GetDeploymentScriptLog(
                        scriptName,
                        ResourceIdUtility.GetResourceGroupName(DeploymentScriptObject.Id),
                        tailParam);
                    break;

                default:
                    throw new PSInvalidOperationException();
                }

                if (!string.IsNullOrEmpty(OutputPath) && !string.IsNullOrEmpty(deploymentScriptLog?.Log))
                {
                    var outputPathWithFileName = Path.Combine(GetValidatedFolderPath(OutputPath),
                                                              $"{deploymentScriptLog.DeploymentScriptName}.txt");

                    // if a file with the same name exists and -Force is not provided, let's ask if we can replace the file.
                    this.ConfirmAction(
                        this.Force || !AzureSession.Instance.DataStore.FileExists(outputPathWithFileName),
                        string.Format(
                            Properties.Resources.DeploymentScriptLogFileExists, scriptName, OutputPath),
                        Properties.Resources.DeploymentScriptShouldProcessString,
                        OutputPath,
                        () =>
                    {
                        //Standardize newline character to be written into file
                        StringBuilder logs        = new StringBuilder();
                        StringReader stringReader = new StringReader(deploymentScriptLog.Log);

                        String line = stringReader.ReadLine();
                        while (line != null)
                        {
                            logs.Append(line);
                            line = stringReader.ReadLine();
                            if (line != null)
                            {
                                logs.Append(Environment.NewLine);
                            }
                        }

                        AzureSession.Instance.DataStore.WriteFile(outputPathWithFileName,
                                                                  logs.ToString());

                        WriteObject(new PsDeploymentScriptLogPath()
                        {
                            Path = outputPathWithFileName
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
        public virtual object GetDynamicParameters()
        {
            if (!this.IsParameterBound(c => c.SkipTemplateParameterPrompt))
            {
                // Resolve the static parameter names for this cmdlet:
                string[] staticParameterNames = this.GetStaticParameterNames();

                if (TemplateObject != null && TemplateObject != templateObject)
                {
                    templateObject = TemplateObject;
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateObject,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateObject,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateFile) &&
                         !TemplateFile.Equals(templateFile, StringComparison.OrdinalIgnoreCase))
                {
                    templateFile = TemplateFile;
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            this.ResolvePath(TemplateFile),
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            this.ResolvePath(TemplateFile),
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateUri) &&
                         !TemplateUri.Equals(templateUri, StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(protectedTemplateUri))
                    {
                        templateUri = TemplateUri;
                    }
                    else
                    {
                        templateUri = protectedTemplateUri;
                    }
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateUri,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateUri,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateSpecId) &&
                         !TemplateSpecId.Equals(templateSpecId, StringComparison.OrdinalIgnoreCase))
                {
                    templateSpecId = TemplateSpecId;
                    ResourceIdentifier resourceIdentifier = new ResourceIdentifier(templateSpecId);
                    if (!resourceIdentifier.ResourceType.Equals("Microsoft.Resources/templateSpecs/versions", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new PSArgumentException("No version found in Resource ID");
                    }

                    if (!string.IsNullOrEmpty(resourceIdentifier.Subscription) &&
                        TemplateSpecsClient.SubscriptionId != resourceIdentifier.Subscription)
                    {
                        // The template spec is in a different subscription than our default
                        // context. Force the client to use that subscription:
                        TemplateSpecsClient.SubscriptionId = resourceIdentifier.Subscription;
                    }

                    var templateSpecVersion = TemplateSpecsClient.TemplateSpecVersions.Get(
                        ResourceIdUtility.GetResourceGroupName(templateSpecId),
                        ResourceIdUtility.GetResourceName(templateSpecId).Split('/')[0],
                        resourceIdentifier.ResourceName);

                    if (!(templateSpecVersion.Template is JObject))
                    {
                        throw new InvalidOperationException("Unexpected type."); // Sanity check
                    }

                    JObject templateObj = (JObject)templateSpecVersion.Template;

                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateObj,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateObj,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
            }

            RegisterDynamicParameters(dynamicParameters);

            return(dynamicParameters);
        }
Пример #22
0
        public override void ExecuteCmdlet()
        {
            ConfirmAction(
                ProjectResources.DeleteDeploymentMessage,
                ResourceGroupName,
                () =>
            {
                var resourceGroupName = !string.IsNullOrEmpty(this.ResourceGroupName) ? this.ResourceGroupName : ResourceIdUtility.GetResourceGroupName(Id);
                var deploymentName    = !string.IsNullOrEmpty(this.Name) ? this.Name : ResourceIdUtility.GetResourceName(Id);

                ResourceManagerSdkClient.DeleteDeploymentAtResourceGroup(resourceGroupName, deploymentName);
                WriteObject(true);
            });
        }
Пример #23
0
        public object GetDynamicParameters()
        {
            if (!this.IsParameterBound(c => c.SkipTemplateParameterPrompt))
            {
                if (TemplateObject != null && TemplateObject != templateObject)
                {
                    templateObject = TemplateObject;
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateObject,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateObject,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateFile) &&
                         !TemplateFile.Equals(templateFile, StringComparison.OrdinalIgnoreCase))
                {
                    templateFile = TemplateFile;
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            this.ResolvePath(TemplateFile),
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            this.ResolvePath(TemplateFile),
                            TemplateParameterObject,
                            TemplateParameterUri,
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateUri) &&
                         !TemplateUri.Equals(templateUri, StringComparison.OrdinalIgnoreCase))
                {
                    templateUri = TemplateUri;
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateUri,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateUri,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateSpecId) &&
                         !TemplateSpecId.Equals(templateSpecId, StringComparison.OrdinalIgnoreCase))
                {
                    templateSpecId = TemplateSpecId;
                    ResourceIdentifier resourceIdentifier = new ResourceIdentifier(templateSpecId);
                    if (!resourceIdentifier.ResourceType.Equals("Microsoft.Resources/templateSpecs/versions", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new PSArgumentException("No version found in Resource ID");
                    }

                    var templateSpecVersion = TemplateSpecsSdkClient.GetTemplateSpec(
                        ResourceIdUtility.GetResourceName(templateSpecId).Split('/')[0],
                        ResourceIdUtility.GetResourceGroupName(templateSpecId),
                        resourceIdentifier.ResourceName).Versions.Single();

                    var templateObj = JObject.Parse(templateSpecVersion.Template);

                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateObj,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateObj,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            MyInvocation.MyCommand.Parameters.Keys.ToArray());
                    }
                }
            }

            RegisterDynamicParameters(dynamicParameters);

            return(dynamicParameters);
        }
Пример #24
0
        public override void ExecuteCmdlet()
        {
            var options = new FilterDeploymentOptions(DeploymentScopeType.ResourceGroup)
            {
                ResourceGroupName = !string.IsNullOrEmpty(this.ResourceGroupName) ? this.ResourceGroupName : ResourceIdUtility.GetResourceGroupName(Id),
                DeploymentName    = !string.IsNullOrEmpty(this.Name) ? this.Name : ResourceIdUtility.GetResourceName(Id)
            };

            ConfirmAction(
                ProjectResources.CancelDeploymentMessage,
                ResourceGroupName,
                () => ResourceManagerSdkClient.CancelDeployment(options));

            WriteObject(true);
        }
        public virtual object GetDynamicParameters()
        {
            if (BicepUtility.IsBicepFile(TemplateFile))
            {
                BuildAndUseBicepTemplate();
            }

            if (!this.IsParameterBound(c => c.SkipTemplateParameterPrompt))
            {
                // Resolve the static parameter names for this cmdlet:
                string[] staticParameterNames = this.GetStaticParameterNames();

                if (TemplateObject != null && TemplateObject != templateObject)
                {
                    templateObject = TemplateObject;
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateObject,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            TemplateObject,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateFile) &&
                         !TemplateFile.Equals(templateFile, StringComparison.OrdinalIgnoreCase))
                {
                    templateFile = TemplateFile;
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            this.ResolvePath(TemplateFile),
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            this.ResolvePath(TemplateFile),
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateUri) &&
                         !TemplateUri.Equals(templateUri, StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(protectedTemplateUri))
                    {
                        templateUri = TemplateUri;
                    }
                    else
                    {
                        templateUri = protectedTemplateUri;
                    }
                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateUri,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateUri,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
                else if (!string.IsNullOrEmpty(TemplateSpecId) &&
                         !TemplateSpecId.Equals(templateSpecId, StringComparison.OrdinalIgnoreCase))
                {
                    templateSpecId = TemplateSpecId;
                    ResourceIdentifier resourceIdentifier = new ResourceIdentifier(templateSpecId);
                    if (!resourceIdentifier.ResourceType.Equals("Microsoft.Resources/templateSpecs/versions", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new PSArgumentException("No version found in Resource ID");
                    }

                    if (!string.IsNullOrEmpty(resourceIdentifier.Subscription) &&
                        TemplateSpecsClient.SubscriptionId != resourceIdentifier.Subscription)
                    {
                        // The template spec is in a different subscription than our default
                        // context. Force the client to use that subscription:
                        TemplateSpecsClient.SubscriptionId = resourceIdentifier.Subscription;
                    }
                    JObject templateObj = (JObject)null;
                    try
                    {
                        var templateSpecVersion = TemplateSpecsClient.TemplateSpecVersions.Get(
                            ResourceIdUtility.GetResourceGroupName(templateSpecId),
                            ResourceIdUtility.GetResourceName(templateSpecId).Split('/')[0],
                            resourceIdentifier.ResourceName);

                        if (!(templateSpecVersion.Template is JObject))
                        {
                            throw new InvalidOperationException("Unexpected type."); // Sanity check
                        }
                        templateObj = (JObject)templateSpecVersion.Template;
                    }
                    catch (TemplateSpecsErrorException e)
                    {
                        //If the templateSpec resourceID is pointing to a non existant resource
                        if (e.Response.StatusCode.Equals(HttpStatusCode.NotFound))
                        {
                            //By returning null, we are introducing parity in the way templateURI and templateSpecId are validated. Gives a cleaner error message in line with the error message for invalid templateURI
                            return(null);
                        }
                        //Throw for any other error that is not due to a 404 for the template resource.
                        throw;
                    }

                    if (string.IsNullOrEmpty(TemplateParameterUri))
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateObj,
                            TemplateParameterObject,
                            this.ResolvePath(TemplateParameterFile),
                            staticParameterNames);
                    }
                    else
                    {
                        dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                            templateObj,
                            TemplateParameterObject,
                            TemplateParameterUri,
                            staticParameterNames);
                    }
                }
            }

            RegisterDynamicParameters(dynamicParameters);

            return(dynamicParameters);
        }
        public override void ExecuteCmdlet()
        {
            try
            {
                // TODO: Update the following to use ??= when we upgrade to C# 8.0
                if (ResourceGroupName == null)
                {
                    ResourceGroupName = ResourceIdUtility.GetResourceGroupName(this.ResourceId);
                }

                if (Name == null)
                {
                    Name = ResourceIdUtility.GetResourceName(this.ResourceId);
                }

                if (Version != null)
                {
                    // This is a version specific update...

                    PackagedTemplate packagedTemplate;

                    switch (ParameterSetName)
                    {
                    case UpdateVersionByIdFromJsonFileParameterSet:
                    case UpdateVersionByNameFromJsonFileParameterSet:
                        string filePath = this.TryResolvePath(TemplateFile);
                        if (!File.Exists(filePath))
                        {
                            throw new PSInvalidOperationException(
                                      string.Format(ProjectResources.InvalidFilePath, TemplateFile)
                                      );
                        }

                        packagedTemplate = TemplateSpecPackagingEngine.Pack(filePath);
                        break;

                    case UpdateVersionByIdFromJsonParameterSet:
                    case UpdateVersionByNameFromJsonParameterSet:
                        JObject parsedTemplate;
                        try
                        {
                            parsedTemplate = JObject.Parse(TemplateJson);
                        }
                        catch
                        {
                            // Check if the user may have inadvertantly passed a file path using "-TemplateJson"
                            // instead of using "-TemplateFile". If they did, display a warning message. Note we
                            // do not currently automatically switch to using a file in this case because if the
                            // JSON string is coming from an external script/source not authored directly by the
                            // caller it could result in a sensitive template being PUT unintentionally:

                            try
                            {
                                string asFilePath = this.TryResolvePath(TemplateJson);
                                if (File.Exists(asFilePath))
                                {
                                    WriteWarning(
                                        $"'{TemplateJson}' was found to exist as a file. Did you mean to use '-TemplateFile' instead?"
                                        );
                                }
                            }
                            catch
                            {
                                // Subsequent failure in the file existence check... Ignore it
                            }

                            throw;
                        }

                        // When we're provided with a raw JSON string for the template we don't
                        // do any special packaging... (ie: we don't pack artifacts because there
                        // is no well known root path):

                        packagedTemplate = new PackagedTemplate
                        {
                            RootTemplate = JObject.Parse(TemplateJson),
                            Artifacts    = new TemplateSpecArtifact[0]
                        };
                        break;

                    default:
                        throw new PSNotSupportedException();
                    }

                    if (!ShouldProcess($"{Name}/versions/{Version}", "Create or Update"))
                    {
                        return;
                    }

                    var templateSpecVersion = TemplateSpecsSdkClient.CreateOrUpdateTemplateSpecVersion(
                        ResourceGroupName,
                        Name,
                        Version,
                        Location,
                        packagedTemplate,
                        templateSpecDescription: Description,
                        templateSpecDisplayName: DisplayName,
                        versionDescription: VersionDescription,
                        templateSpecTags: Tag, // Note: Only applied if template spec doesn't exist
                        versionTags: Tag
                        );

                    WriteObject(templateSpecVersion);
                }
                else
                {
                    // This is an update to the root template spec only:

                    if (!ShouldProcess(Name, "Create or Update"))
                    {
                        return;
                    }

                    var templateSpec = TemplateSpecsSdkClient.CreateOrUpdateTemplateSpec(
                        ResourceGroupName,
                        Name,
                        Location,
                        templateSpecDescription: Description,
                        templateSpecDisplayName: DisplayName,
                        tags: Tag
                        );

                    // As the root template spec is a seperate resource type, it won't contain version
                    // details. To provide more information to the user, let's get the template spec
                    // with all of its version details:

                    var templateSpecWithVersions =
                        TemplateSpecsSdkClient.GetTemplateSpec(templateSpec.Name, templateSpec.ResourceGroupName);

                    WriteObject(templateSpecWithVersions);
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }