Example #1
0
        /// <summary>
        /// Gets the resource Id using the <c>ParentResource</c>.
        /// </summary>
        private string GetResourceIdWithParentResource()
        {
            if (this.SubscriptionId.Length != 1)
            {
                throw new ArgumentException();
            }

#pragma warning disable 618

            return(ResourceIdUtility.GetResourceId(
                       subscriptionId: this.SubscriptionId.First(),
                       resourceGroupName: this.ResourceGroupName,
                       parentResource: this.ParentResource,
                       resourceType: this.ResourceType,
                       resourceName: this.ResourceName));

#pragma warning restore 618
        }
        /// <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);
        }
        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);

                        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()
        {
            ConfirmAction(
                ProjectResources.DeleteDeploymentMessage,
                Name,
                () =>
            {
                var deploymentName = !string.IsNullOrEmpty(this.Name)
                        ? this.Name
                        : !string.IsNullOrEmpty(this.Id) ? ResourceIdUtility.GetResourceName(this.Id) : this.InputObject.DeploymentName;

                ResourceManagerSdkClient.DeleteDeploymentAtSubscriptionScope(deploymentName);

                if (this.PassThru.IsPresent)
                {
                    WriteObject(true);
                }
            });
        }
Example #5
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();

            var policyAssignmentObject = new PolicyAssignment
            {
                Name       = this.Name ?? ResourceIdUtility.GetResourceName(this.Id),
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null
                        ? resource.Properties["displayName"].ToString()
                        : null),
                    Scope = resource.Properties["scope"].ToString(),
                    PolicyDefinitionId = resource.Properties["policyDefinitionId"].ToString()
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
        public override void ExecuteCmdlet()
        {
            var options = new FilterDeploymentOptions(DeploymentScopeType.Subscription)
            {
                DeploymentName = !string.IsNullOrEmpty(this.Name)
                    ? this.Name
                    : !string.IsNullOrEmpty(this.Id) ? ResourceIdUtility.GetResourceName(this.Id) : this.InputObject.DeploymentName
            };

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

            if (this.PassThru.IsPresent)
            {
                WriteObject(true);
            }
        }
        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);
        }
Example #8
0
        public PSResource(Resource <JToken> resource) : this(
                resource.Id,
                resource.Name,
                resource.Kind,
                resource.Location,
                string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceType(resource.Id),
                resource.Identity == null ? null : new Identity(resource.Identity.PrincipalId, resource.Identity.TenantId),
                resource.Properties?.ToPsObject(),
                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
        },
                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
        },
                TagsHelper.GetTagsDictionary(TagsHelper.GetTagsHashtable(resource.Tags))
                )
        {
            this.CreatedTime = resource.CreatedTime;
            this.ChangedTime = resource.ChangedTime;

            this.SubscriptionId        = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetSubscriptionId(resource.Id);
            this.ResourceGroupName     = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetResourceGroupName(resource.Id);
            this.ExtensionResourceName = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceName(resource.Id);
            this.ExtensionResourceType = string.IsNullOrEmpty(resource.Id) ? null : ResourceIdUtility.GetExtensionResourceType(resource.Id);
            this.ETag = resource.ETag;
            if (resource.Identity != null)
            {
                if (Enum.TryParse(resource.Identity.Type, out Management.ResourceManager.Models.ResourceIdentityType type))
                {
                    this.Identity.Type = type;
                }
            }
        }
Example #9
0
        protected override void OnProcessRecord()
        {
            var options = new FilterDeploymentOptions(DeploymentScopeType.Tenant)
            {
                DeploymentName = !string.IsNullOrEmpty(this.Name)
                    ? this.Name
                    : !string.IsNullOrEmpty(this.Id) ? ResourceIdUtility.GetDeploymentName(this.Id) : this.InputObject.DeploymentName
            };

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

            if (this.PassThru.IsPresent)
            {
                WriteObject(true);
            }
        }
        /// <summary>
        /// Populates the permissions on the resource.
        /// </summary>
        /// <param name="resource">The resource.</param>
        private async Task PopulatePermissions(PSObject resource)
        {
            try
            {
                var resourceId = resource.Properties["ResourceId"].Value.ToString();

                var resourceCollectionId = resourceId + ResourceIdUtility
                                           .GetResourceCollectionId(
                    subscriptionId: null,
                    resourceGroupName: null,
                    resourceType: null,
                    extensionResourceType: "Microsoft.Authorization/permissions");

                var apiVersion = await ApiVersionHelper
                                 .DetermineApiVersion(
                    profile : this.Profile,
                    providerNamespace : "Microsoft.Authorization",
                    resourceType : "permissions",
                    cancellationToken : this.CancellationToken.Value,
                    pre : this.Pre)
                                 .ConfigureAwait(continueOnCapturedContext: false);

                var permissions = PaginatedResponseHelper.Enumerate(
                    getFirstPage: () => this.GetPermissions(permissionCheckId: resourceCollectionId, apiVersion: apiVersion),
                    getNextPage: nextLink => this.GetNextLink <Permission>(nextLink),
                    cancellationToken: this.CancellationToken);

                resource.Properties.Add(new PSNoteProperty("Permissions", permissions));
            }
            catch (Exception ex)
            {
                if (ex.IsFatal())
                {
                    throw;
                }

                ex = (ex is AggregateException)
                    ? (ex as AggregateException).Flatten()
                    : ex;

                this.errors.Add(new ErrorRecord(ex, "ErrorExpandingPermissions", ErrorCategory.CloseError, resource));
            }
        }
        public override void ExecuteCmdlet()
        {
            try
            {
                ResourceIdentifier resourceIdentifier = (ResourceId != null)
                    ? new ResourceIdentifier(ResourceId)
                    : null;

                ResourceGroupName = ResourceGroupName ?? resourceIdentifier.ResourceGroupName;
                Name = Name ?? ResourceIdUtility.GetResourceName(ResourceId);

                if (ResourceId != null && Version == null)
                {
                    // Check if the resource id includes a version...
                    string resourceType = resourceIdentifier.ResourceType;
                    if (!string.IsNullOrEmpty(resourceType) &&
                        resourceType.Equals("Microsoft.Resources/templateSpecs/versions", StringComparison.OrdinalIgnoreCase))
                    {
                        // It does...
                        Version = resourceIdentifier.ResourceName;
                    }
                }

                string confirmationMessage = (Version != null)
                    ? $"Are you sure you want to remove version '{Version}' of Template Spec '{Name}'"
                    : $"Are you sure you want to remove Template Spec '{Name}'";

                ConfirmAction(
                    Force.IsPresent,
                    confirmationMessage,
                    "Deleting Template Spec...",
                    Version ?? Name,
                    () => TemplateSpecsSdkClient.DeleteTemplateSpec(ResourceGroupName, Name, Version)
                    );

                WriteObject(true);
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
        public override void ExecuteCmdlet()
        {
            try
            {
                switch (ParameterSetName)
                {
                case RemoveDeploymentScriptByName:
                    if (ShouldProcess(Name, "Remove Deployment Script"))
                    {
                        DeploymentScriptsSdkClient.DeleteDeploymentScript(Name, ResourceGroupName);
                    }
                    break;

                case RemoveDeploymentScriptByResourceId:
                    if (ShouldProcess(Name, "Remove Deployment Script"))
                    {
                        DeploymentScriptsSdkClient.DeleteDeploymentScript(ResourceIdUtility.GetResourceName(this.Id),
                                                                          ResourceIdUtility.GetResourceGroupName(this.Id));
                    }
                    break;

                case RemoveDeploymentScriptByInputObject:
                    if (ShouldProcess(Name, "Remove Deployment Script"))
                    {
                        DeploymentScriptsSdkClient.DeleteDeploymentScript(InputObject.Name, ResourceIdUtility.GetResourceGroupName(InputObject.Id));
                    }
                    break;

                default:
                    throw new PSInvalidOperationException();
                }

                if (PassThru.IsPresent)
                {
                    WriteObject(true);
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
        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()
        {
            ConfirmAction(
                ProjectResources.DeleteDeploymentMessage,
                Name,
                () =>
            {
                var options = new FilterDeploymentOptions(DeploymentScopeType.Tenant)
                {
                    DeploymentName = !string.IsNullOrEmpty(this.Name)
                            ? this.Name
                            : !string.IsNullOrEmpty(this.Id) ? ResourceIdUtility.GetDeploymentName(this.Id) : this.InputObject.DeploymentName
                };

                this.ResourceManagerSdkClient.DeleteDeploymentAtTenantScope(options.DeploymentName);

                if (this.PassThru.IsPresent)
                {
                    WriteObject(true);
                }
            });
        }
        /// <summary>
        /// Gets the resource Id
        /// </summary>
        private string GetResourceId()
        {
            var subscriptionId = DefaultContext.Subscription.Id;

            if (string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.Scope))
            {
                return(string.Format("/subscriptions/{0}/providers/{1}",
                                     subscriptionId.ToString(),
                                     Constants.MicrosoftAuthorizationPolicyAssignmentType));
            }
            else if (string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope))
            {
                return(ResourceIdUtility.GetResourceId(
                           resourceId: this.Scope,
                           extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType,
                           extensionResourceName: null));
            }
            return(ResourceIdUtility.GetResourceId(
                       resourceId: this.Scope,
                       extensionResourceType: Constants.MicrosoftAuthorizationPolicyAssignmentType,
                       extensionResourceName: this.Name));
        }
        public override void ExecuteCmdlet()
        {
            PsDeploymentScriptLog deploymentScriptLog;
            int tailParam = this.IsParameterBound(c => c.Tail) ? Tail : 0;

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

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

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

                default:
                    throw new PSInvalidOperationException();
                }

                WriteObject(deploymentScriptLog);
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
Example #18
0
        /// <summary>
        /// Queries the ARM cache and returns the cached resource that match the query specified.
        /// </summary>
        private async Task <ResponseWithContinuation <JObject[]> > GetResources()
        {
            string resourceId = this.Id ?? this.GetResourceId();

            var apiVersion = await this
                             .DetermineApiVersion(resourceId : resourceId)
                             .ConfigureAwait(continueOnCapturedContext: false);

            if (!string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)))
            {
                var resource = await this
                               .GetResourcesClient()
                               .GetResource <JObject>(
                    resourceId: resourceId,
                    apiVersion: apiVersion,
                    cancellationToken: this.CancellationToken.Value)
                               .ConfigureAwait(continueOnCapturedContext: false);

                ResponseWithContinuation <JObject[]> retVal;
                return(resource.TryConvertTo(out retVal) && retVal.Value != null
                    ? retVal
                    : new ResponseWithContinuation <JObject[]> {
                    Value = resource.AsArray()
                });
            }
            else
            {
                return(await this
                       .GetResourcesClient()
                       .ListObjectColleciton <JObject>(
                           resourceCollectionId: resourceId,
                           apiVersion: apiVersion,
                           cancellationToken: this.CancellationToken.Value)
                       .ConfigureAwait(continueOnCapturedContext: false));
            }
        }
        /// <summary>
        /// Executes the cmdlet
        /// </summary>
        private void RunCmdlet()
        {
            var resourceIdsToUse = this.resourceIds
                                   .Concat(this.ResourceId)
                                   .DistinctArray(StringComparer.InvariantCultureIgnoreCase);

            this.DestinationSubscriptionId = this.DestinationSubscriptionId ?? DefaultContext.Subscription.Id;

            var sourceResourceGroups = resourceIdsToUse
                                       .Select(resourceId => ResourceIdUtility.GetResourceGroupId(resourceId))
                                       .Where(resourceGroupId => !string.IsNullOrWhiteSpace(resourceGroupId))
                                       .DistinctArray(StringComparer.InvariantCultureIgnoreCase);

            var count = sourceResourceGroups.Count();

            if (count == 0)
            {
                throw new InvalidOperationException("At least one valid resource Id must be provided.");
            }
            else if (count > 1)
            {
                throw new InvalidOperationException(
                          string.Format("The resources being moved must all reside in the same resource group. The resources: {0}", resourceIdsToUse.ConcatStrings(", ")));
            }

            var sourceResourceGroup = sourceResourceGroups.Single();

            var destinationResourceGroup = ResourceIdUtility.GetResourceId(
                subscriptionId: this.DestinationSubscriptionId,
                resourceGroupName: this.DestinationResourceGroupName,
                resourceName: null,
                resourceType: null);

            this.ConfirmAction(
                this.Force,
                string.Format(
                    "Are you sure you want to move these resources to the resource group '{0}' the resources: {1}",
                    destinationResourceGroup,
                    Environment.NewLine.AsArray().Concat(resourceIdsToUse).ConcatStrings(Environment.NewLine)),
                "Moving the resources.",
                destinationResourceGroup,
                () =>
            {
                var apiVersion = this
                                 .DetermineApiVersion(
                    providerNamespace: Constants.MicrosoftResourceNamesapce,
                    resourceType: Constants.ResourceGroups)
                                 .Result;

                var parameters = new ResourceBatchMoveParameters
                {
                    Resources           = resourceIdsToUse,
                    TargetResourceGroup = destinationResourceGroup,
                };

                var operationResult = this.GetResourcesClient()
                                      .InvokeActionOnResource <JObject>(
                    resourceId: sourceResourceGroup,
                    action: Constants.MoveResources,
                    apiVersion: apiVersion,
                    parameters: parameters.ToJToken(),
                    cancellationToken: this.CancellationToken.Value)
                                      .Result;

                var managementUri = this.GetResourcesClient()
                                    .GetResourceManagementRequestUri(
                    resourceId: destinationResourceGroup,
                    apiVersion: apiVersion,
                    action: Constants.MoveResources);

                var activity = string.Format("POST {0}", managementUri.PathAndQuery);

                var result = this
                             .GetLongRunningOperationTracker(
                    activityName: activity,
                    isResourceCreateOrUpdate: false)
                             .WaitOnOperation(operationResult: operationResult);

                this.TryConvertAndWriteObject(result);
            });
        }
        /// <summary>
        /// Executes the cmdlet
        /// </summary>
        private void RunCmdlet()
        {
            var resourceIdsToUse = this.resourceIds
                                   .Concat(this.ResourceId)
                                   .DistinctArray(StringComparer.InvariantCultureIgnoreCase);

            this.DestinationSubscriptionId = this.Profile.Context.Subscription.Id;

            var resourceGroup = ResourceIdUtility.GetResourceId(
                subscriptionId: this.DestinationSubscriptionId,
                resourceGroupName: this.DestinationResourceGroupName,
                resourceName: null,
                resourceType: null);

            this.ConfirmAction(
                this.Force,
                string.Format(
                    "Are you sure you want to move these resources to the resource group '{0}' the resources: {1}",
                    resourceGroup,
                    Environment.NewLine.AsArray().Concat(resourceIdsToUse).ConcatStrings(Environment.NewLine)),
                "Moving the resources.",
                resourceGroup,
                () =>
            {
                var apiVersion = this
                                 .DetermineApiVersion(
                    providerNamespace: Constants.MicrosoftResourceNamesapce,
                    resourceType: Constants.ResourceGroups)
                                 .Result;

                var parameters = new ResourceBatchMoveParameters
                {
                    Resources           = resourceIdsToUse,
                    TargetResourceGroup = resourceGroup,
                };

                var operationResult = this.GetResourcesClient()
                                      .InvokeActionOnResource <JObject>(
                    resourceId: resourceGroup,
                    action: Constants.Move,
                    apiVersion: apiVersion,
                    parameters: parameters.ToJToken(),
                    cancellationToken: this.CancellationToken.Value)
                                      .Result;

                var managementUri = this.GetResourcesClient()
                                    .GetResourceManagementRequestUri(
                    resourceId: resourceGroup,
                    apiVersion: apiVersion,
                    action: Constants.Move);

                var activity = string.Format("POST {0}", managementUri.PathAndQuery);

                var result = this
                             .GetLongRunningOperationTracker(
                    activityName: activity,
                    isResourceCreateOrUpdate: false)
                             .WaitOnOperation(operationResult: operationResult);

                this.WriteObject(result);
            });
        }
        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);
            }
        }
Example #22
0
        protected override void OnProcessRecord()
        {
            FilterDeploymentOptions options = new FilterDeploymentOptions(DeploymentScopeType.Tenant)
            {
                DeploymentName = this.Name ?? (string.IsNullOrEmpty(this.Id) ? null : ResourceIdUtility.GetDeploymentName(this.Id))
            };

            WriteObject(ResourceManagerSdkClient.FilterDeployments(options), true);
        }
        public override void ExecuteCmdlet()
        {
            PsDeploymentScriptLog deploymentScriptLog;
            int tailParam = this.IsParameterBound(c => c.Tail) ? Tail : 0;

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

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

                case SaveDeploymentScriptLogByInputObject:
                    deploymentScriptLog = DeploymentScriptsSdkClient.GetDeploymentScriptLog(
                        DeploymentScriptInputObject.Name,
                        ResourceIdUtility.GetResourceGroupName(DeploymentScriptInputObject.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, Name, OutputPath),
                        Properties.Resources.DeploymentScriptShouldProcessString,
                        OutputPath,
                        () =>
                    {
                        AzureSession.Instance.DataStore.WriteFile(outputPathWithFileName,
                                                                  deploymentScriptLog.Log);

                        WriteObject(new PsDeploymentScriptLogPath()
                        {
                            Path = outputPathWithFileName
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                WriteExceptionError(ex);
            }
        }
        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);
        }
Example #25
0
        public override void ExecuteCmdlet()
        {
            FilterDeploymentOptions options = new FilterDeploymentOptions(DeploymentScopeType.Subscription)
            {
                DeploymentName = this.Name ?? (string.IsNullOrEmpty(this.Id) ? null : ResourceIdUtility.GetResourceName(this.Id))
            };

            WriteObject(ResourceManagerSdkClient.FilterDeployments(options), true);
        }
Example #26
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);
        }
 /// <summary>
 /// Returns true if it is a single policy assignment get
 /// </summary>
 /// <param name="resourceId"></param>
 private bool IsResourceGet(string resourceId)
 {
     return((!string.IsNullOrEmpty(this.Name) && !string.IsNullOrEmpty(this.Scope)) ||
            !string.IsNullOrEmpty(ResourceIdUtility.GetResourceName(resourceId)));
 }
Example #28
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);
            });
        }
        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);
        }
Example #30
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);
        }