private Assignment CreateBlueprintAssignment(PublishedBlueprint sealedBlueprint)
 {
     return(new Assignment
     {
         BlueprintId = sealedBlueprint.Id,
         Identity = new ManagedServiceIdentity {
             Type = Constants.ManagedServiceIdentityType.SystemAssigned
         },
         Location = "EastUS",
         ResourceGroups = new OrdinalStringDictionary <ResourceGroupValue>
         {
             { "vNicResourceGroup", new ResourceGroupValue {
                   Name = "default-virtual-networks", Location = "EastUS"
               } },
         },
         Parameters = new OrdinalStringDictionary <ParameterValueBase>
         {
             { "vNetName", new ParameterValue {
                   Value = "DefaultPublicFacingNetwork"
               } },
             { "defaultLocation", new ParameterValue {
                   Value = "East US"
               } },
             { "defaultCostCenter", new ParameterValue {
                   Value = "Contoso/RnD/Dev/986754"
               } }
         }
     });
 }
Пример #2
0
        private Assignment CreateBlueprintAssignment(PublishedBlueprint sealedBlueprint, string subscriptionId = null)
        {
            string scope = !string.IsNullOrEmpty(subscriptionId)
                ? string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId)
                : null;

            return(new Assignment
            {
                BlueprintId = sealedBlueprint.Id,
                Identity = new ManagedServiceIdentity {
                    Type = Constants.ManagedServiceIdentityType.SystemAssigned
                },
                Location = "EastUS",
                Scope = scope,
                ResourceGroups = new OrdinalStringDictionary <ResourceGroupValue>
                {
                    { "vNicResourceGroup", new ResourceGroupValue {
                          Name = "default-virtual-networks", Location = "EastUS"
                      } },
                },
                Parameters = new OrdinalStringDictionary <ParameterValue>
                {
                    { "vNetName", new ParameterValue {
                          Value = "DefaultPublicFacingNetwork"
                      } },
                    { "defaultLocation", new ParameterValue {
                          Value = "East US"
                      } },
                    { "defaultCostCenter", new ParameterValue {
                          Value = "Contoso/RnD/Dev/986754"
                      } }
                }
            });
        }
Пример #3
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Utils.GetDefinitionLocationId(Blueprint.Scope), string.Format(Resources.PublishBlueprintShouldProcessString, Blueprint.Name)))
            {
                try
                {
                    // parameters property is placeholder here, backend strips this information and publishes the latest master. It is needed in the payload since swagger calls it required.
                    var publishedBlueprintObjForChangeNotes = new PublishedBlueprint(
                        parameters: new Dictionary <string, ParameterDefinition>(), changeNotes: ChangeNote);

                    WriteObject(BlueprintClient.CreatePublishedBlueprint(Blueprint.Scope, Blueprint.Name, Version, publishedBlueprintObjForChangeNotes));
                }
                catch (Exception ex)
                {
                    WriteExceptionError(ex);
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Publish a new version of the blueprint definition with the latest
        /// artifacts. Published blueprint definitions are immutable.
        /// </summary>
        /// <param name='resourceScope'>
        /// The scope of the resource. Valid scopes are: management group (format:
        /// '/providers/Microsoft.Management/managementGroups/{managementGroup}'),
        /// subscription (format: '/subscriptions/{subscriptionId}').
        /// </param>
        /// <param name='blueprintName'>
        /// Name of the blueprint definition.
        /// </param>
        /// <param name='versionId'>
        /// Version of the published blueprint definition.
        /// </param>
        /// <param name='publishedBlueprint'>
        /// Published Blueprint to create or update.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <PublishedBlueprint> > CreateWithHttpMessagesAsync(string resourceScope, string blueprintName, string versionId, PublishedBlueprint publishedBlueprint = default(PublishedBlueprint), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (resourceScope == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceScope");
            }
            if (blueprintName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "blueprintName");
            }
            if (versionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "versionId");
            }
            if (publishedBlueprint != null)
            {
                publishedBlueprint.Validate();
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceScope", resourceScope);
                tracingParameters.Add("blueprintName", blueprintName);
                tracingParameters.Add("versionId", versionId);
                tracingParameters.Add("publishedBlueprint", publishedBlueprint);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}/versions/{versionId}").ToString();

            _url = _url.Replace("{resourceScope}", resourceScope);
            _url = _url.Replace("{blueprintName}", System.Uri.EscapeDataString(blueprintName));
            _url = _url.Replace("{versionId}", System.Uri.EscapeDataString(versionId));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (publishedBlueprint != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(publishedBlueprint, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 201)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <PublishedBlueprint>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <PublishedBlueprint>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        /// <summary>
        /// Create a PSPublishedBlueprint object from a PublishedBlueprint.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="scope">Subscription or management group the blueprint belongs to.</param>
        /// <returns>A new PSPublishedBlueprint object</returns>
        internal static PSPublishedBlueprint FromPublishedBlueprintModel(PublishedBlueprint model, string scope)
        {
            var psBlueprint = new PSPublishedBlueprint
            {
                Id             = model.Id,
                Name           = model.BlueprintName,
                Scope          = scope,
                DisplayName    = model.DisplayName,
                Description    = model.Description,
                Status         = new PSBlueprintStatus(),
                TargetScope    = PSBlueprintTargetScope.Unknown,
                Parameters     = new Dictionary <string, PSParameterDefinition>(),
                ResourceGroups = new Dictionary <string, PSResourceGroupDefinition>(),
                Version        = model.Name, // Name is the version in PublishedBlueprint object.
                ChangeNotes    = model.ChangeNotes
            };

            psBlueprint.Status.TimeCreated = model.Status.TimeCreated;

            psBlueprint.Status.LastModified = model.Status.LastModified;


            if (Enum.TryParse(model.TargetScope, true, out PSBlueprintTargetScope targetScope))
            {
                psBlueprint.TargetScope = targetScope;
            }
            else
            {
                psBlueprint.TargetScope = PSBlueprintTargetScope.Unknown;
            }

            foreach (var item in model.Parameters)
            {
                psBlueprint.Parameters.Add(item.Key,
                                           new PSParameterDefinition
                {
                    Type          = item.Value.Type,
                    DisplayName   = item.Value.DisplayName,
                    Description   = item.Value.Description,
                    StrongType    = item.Value.StrongType,
                    DefaultValue  = item.Value.DefaultValue,
                    AllowedValues = (item.Value.AllowedValues != null) ? item.Value.AllowedValues.ToList() : null
                });
            }

            foreach (var item in model.ResourceGroups)
            {
                psBlueprint.ResourceGroups.Add(item.Key,
                                               new PSResourceGroupDefinition
                {
                    Name        = item.Value.Name,
                    Location    = item.Value.Location,
                    DisplayName = item.Value.DisplayName,
                    Description = item.Value.Description,
                    StrongType  = item.Value.StrongType,
                    DependsOn   = item.Value.DependsOn.ToList()
                });
            }

            if (psBlueprint.Scope.StartsWith("/subscriptions"))
            {
                psBlueprint.SubscriptionId = Utils.GetDefinitionLocationId(scope);
            }
            else
            {
                psBlueprint.ManagementGroupId = Utils.GetDefinitionLocationId(scope);
            }

            return(psBlueprint);
        }
Пример #6
0
 /// <summary>
 /// Publish a new version of the blueprint definition with the latest
 /// artifacts. Published blueprint definitions are immutable.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='scope'>
 /// The scope of the resource. Valid scopes are: management group (format:
 /// '/providers/Microsoft.Management/managementGroups/{managementGroup}'),
 /// subscription (format: '/subscriptions/{subscriptionId}'). For blueprint
 /// assignments management group scope is reserved for future use.
 /// </param>
 /// <param name='blueprintName'>
 /// Name of the blueprint definition.
 /// </param>
 /// <param name='versionId'>
 /// Version of the published blueprint definition.
 /// </param>
 /// <param name='publishedBlueprint'>
 /// Published Blueprint to create or update.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <PublishedBlueprint> CreateAsync(this IPublishedBlueprintsOperations operations, string scope, string blueprintName, string versionId, PublishedBlueprint publishedBlueprint = default(PublishedBlueprint), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(scope, blueprintName, versionId, publishedBlueprint, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Пример #7
0
 /// <summary>
 /// Publish a new version of the blueprint definition with the latest
 /// artifacts. Published blueprint definitions are immutable.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='scope'>
 /// The scope of the resource. Valid scopes are: management group (format:
 /// '/providers/Microsoft.Management/managementGroups/{managementGroup}'),
 /// subscription (format: '/subscriptions/{subscriptionId}'). For blueprint
 /// assignments management group scope is reserved for future use.
 /// </param>
 /// <param name='blueprintName'>
 /// Name of the blueprint definition.
 /// </param>
 /// <param name='versionId'>
 /// Version of the published blueprint definition.
 /// </param>
 /// <param name='publishedBlueprint'>
 /// Published Blueprint to create or update.
 /// </param>
 public static PublishedBlueprint Create(this IPublishedBlueprintsOperations operations, string scope, string blueprintName, string versionId, PublishedBlueprint publishedBlueprint = default(PublishedBlueprint))
 {
     return(operations.CreateAsync(scope, blueprintName, versionId, publishedBlueprint).GetAwaiter().GetResult());
 }
Пример #8
0
        /// <summary>
        /// Publish a new version of the Blueprint with the latest artifacts. Published
        /// Blueprints are immutable.
        /// </summary>
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='subscriptionId'>
        /// azure subscriptionId, which we save the blueprint to.
        /// </param>
        /// <param name='blueprintName'>
        /// name of the blueprint.
        /// </param>
        /// <param name='versionId'>
        /// version of the published blueprint.
        /// </param>
        /// <param name='publishedBlueprint'>
        /// published blueprint object
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static async Task <PublishedBlueprint> CreateInSubscriptionAsync(this IPublishedBlueprintsOperations operations, string subscriptionId, string blueprintName, string versionId, PublishedBlueprint publishedBlueprint = default(PublishedBlueprint), CancellationToken cancellationToken = default(CancellationToken))
        {
            var scope = string.Format(Constants.ResourceScopes.SubscriptionScope, subscriptionId);

            using (var _result = await operations.CreateWithHttpMessagesAsync(scope, blueprintName, versionId, publishedBlueprint, null, cancellationToken).ConfigureAwait(false))
            {
                return(_result.Body);
            }
        }
Пример #9
0
 public PSPublishedBlueprint CreatePublishedBlueprint(string scope, string name, string version, PublishedBlueprint publishedBP)
 {
     return(PSPublishedBlueprint.FromPublishedBlueprintModel(blueprintManagementClient.PublishedBlueprints.Create(scope, name, version, publishedBP), scope));
 }