/// <summary> /// Converts a template spec model from the Azure SDK to the powershell /// exposed template spec model. /// </summary> /// <param name="templateSpecVersion">The Azure SDK template spec model</param> /// <returns>The converted model or null if no model was specified</returns> internal static PSTemplateSpecVersion FromAzureSDKTemplateSpecVersion( TemplateSpecVersion templateSpecVersion) { if (templateSpecVersion == null) { return(null); } var psTemplateSpecVersion = new PSTemplateSpecVersion { CreationTime = templateSpecVersion.SystemData.CreatedAt, Id = templateSpecVersion.Id, LastModifiedTime = templateSpecVersion.SystemData.LastModifiedAt, Name = templateSpecVersion.Name, Description = templateSpecVersion.Description, Tags = templateSpecVersion.Tags == null ? new Dictionary <string, string>() : new Dictionary <string, string>(templateSpecVersion.Tags), // Note: Cast is redundant, but present for clarity reasons: MainTemplate = ((JToken)templateSpecVersion.MainTemplate).ToString() }; if (templateSpecVersion.LinkedTemplates?.Any() == true) { foreach (LinkedTemplateArtifact artifact in templateSpecVersion.LinkedTemplates) { psTemplateSpecVersion.LinkedTemplates.Add( PSTemplateSpecTemplateArtifact.FromAzureSDKTemplateSpecTemplateArtifact(artifact)); } } return(psTemplateSpecVersion); }
public PackagedTemplate(TemplateSpecVersion versionModel) { this.RootTemplate = (JObject)versionModel?.MainTemplate; this.Artifacts = versionModel?.LinkedTemplates?.ToArray() ?? new LinkedTemplateArtifact[0]; this.UIFormDefinition = (JObject)versionModel?.UiFormDefinition; }
public PSTemplateSpec GetTemplateSpec(string templateSpecName, string resourceGroupName, string templateSpecVersion = null) { var templateSpec = this.GetAzureSdkTemplateSpec(resourceGroupName, templateSpecName); if (templateSpecVersion == null) { List <TemplateSpecVersion> allVersions = new List <TemplateSpecVersion>(); var versionPage = TemplateSpecsClient.TemplateSpecVersions.List(resourceGroupName, templateSpecName); allVersions.AddRange(versionPage); while (versionPage.NextPageLink != null) { versionPage = TemplateSpecsClient.TemplateSpecVersions.ListNext(versionPage.NextPageLink); allVersions.AddRange(versionPage); } return(new PSTemplateSpec(templateSpec, allVersions.ToArray())); } // We have a specific version specified: TemplateSpecVersion specificVersion = TemplateSpecsClient.TemplateSpecVersions.Get( resourceGroupName, templateSpecName, templateSpecVersion ); return(new PSTemplateSpec(templateSpec, new[] { specificVersion })); }
public void ResolvesDynamicParametersWithCrossSubTemplateSpec() { const string templateSpecSubscriptionId = "10000000-0000-0000-0000-000000000000"; const string templateSpecRGName = "someRG"; const string templateSpecName = "myTemplateSpec"; const string templateSpecVersion = "v1"; string templateSpecId = $"/subscriptions/{templateSpecSubscriptionId}/" + $"resourceGroups/{templateSpecRGName}/providers/Microsoft.Resources/" + $"templateSpecs/{templateSpecName }/versions/{templateSpecVersion}"; // Ensure our template file path is normalized for the current system: var normalizedTemplateFilePath = (Path.DirectorySeparatorChar != '\\') ? templateFile.Replace('\\', Path.DirectorySeparatorChar) // Other/Unix based : templateFile; // Windows based (already valid) var templateContentForTest = File.ReadAllText(normalizedTemplateFilePath); var template = JsonConvert.DeserializeObject <TemplateFile>(templateContentForTest); templateSpecsVersionOperationsMock.Setup(f => f.GetWithHttpMessagesAsync( templateSpecRGName, templateSpecName, templateSpecVersion, null, new CancellationToken())) .Returns(() => { // We should only be getting this template spec from the expected subscription: Assert.Equal(templateSpecSubscriptionId, templateSpecsClientMock.Object.SubscriptionId); var versionToReturn = new TemplateSpecVersion( location: "westus2", id: templateSpecId, name: templateSpecVersion, type: "Microsoft.Resources/templateSpecs/versions", template: JObject.Parse(templateContentForTest) ); return(Task.Factory.StartNew(() => new AzureOperationResponse <TemplateSpecVersion>() { Body = versionToReturn } )); }); cmdlet.ResourceGroupName = resourceGroupName; cmdlet.Name = deploymentName; cmdlet.TemplateSpecId = templateSpecId; var dynamicParams = cmdlet.GetDynamicParameters() as RuntimeDefinedParameterDictionary; dynamicParams.Should().NotBeNull(); dynamicParams.Count().Should().Be(template.Parameters.Count); dynamicParams.Keys.Should().Contain(template.Parameters.Keys); }
private ITemplateSpecVersionProvider CreateMockTemplateSpecVersionProvider( ArmClient armClient, TemplateSpecVersion templateSpecVersion) { var templateSpecVersionProvider = StrictMock.Of <ITemplateSpecVersionProvider>(); templateSpecVersionProvider .Setup(x => x.GetTemplateSpecVersion(armClient, It.IsAny <ResourceIdentifier>())) .Returns(templateSpecVersion); return(templateSpecVersionProvider.Object); }
public override void ExecuteCmdlet() { try { ResourceIdentifier resourceIdentifier = (ResourceId != null) ? new ResourceIdentifier(ResourceId) : null; ResourceGroupName = ResourceGroupName ?? resourceIdentifier.ResourceGroupName; Name = Name ?? ResourceIdUtility.GetResourceName(ResourceId); // Get the template spec version model from the SDK: TemplateSpecVersion specificVersion = TemplateSpecsSdkClient.TemplateSpecsClient.TemplateSpecVersions.Get( ResourceGroupName, Name, Version ); // Get the parent template spec from the SDK. We do this because we want to retrieve the // template spec name with its proper casing for naming our main template output file (the // Name parameter may have mismatched casing): TemplateSpec parentTemplateSpec = TemplateSpecsSdkClient.TemplateSpecsClient.TemplateSpecs.Get(ResourceGroupName, Name); PackagedTemplate packagedTemplate = new PackagedTemplate(specificVersion); // TODO: Handle overwriting prompts... // Ensure our output path is resolved based on the current powershell working // directory instead of the current process directory: OutputFolder = ResolveUserPath(OutputFolder); string mainTemplateFileName = $"{parentTemplateSpec.Name}.{specificVersion.Name}.json"; string uiFormDefinitionFileName = $"{parentTemplateSpec.Name}.{specificVersion.Name}.uiformdefinition.json"; string fullRootTemplateFilePath = Path.GetFullPath( Path.Combine(OutputFolder, mainTemplateFileName) ); if (ShouldProcess(specificVersion.Id, $"Export to '{fullRootTemplateFilePath}'")) { TemplateSpecPackagingEngine.Unpack( packagedTemplate, OutputFolder, mainTemplateFileName, uiFormDefinitionFileName); } WriteObject(PowerShellUtilities.ConstructPSObject(null, "Path", fullRootTemplateFilePath)); } catch (Exception ex) { WriteExceptionError(ex); } }
public async Task Get() { string rgName = Recording.GenerateAssetName("testRg-3-"); ResourceGroupData rgData = new ResourceGroupData(Location.WestUS2); var lro = await Client.DefaultSubscription.GetResourceGroups().CreateOrUpdateAsync(rgName, rgData); ResourceGroup rg = lro.Value; string templateSpecName = Recording.GenerateAssetName("templateSpec-G-"); TemplateSpecData templateSpecData = CreateTemplateSpecData(templateSpecName); TemplateSpec templateSpec = (await rg.GetTemplateSpecs().CreateOrUpdateAsync(templateSpecName, templateSpecData)).Value; const string version = "v1"; TemplateSpecVersionData templateSpecVersionData = CreateTemplateSpecVersionData(); TemplateSpecVersion templateSpecVersion = (await templateSpec.GetTemplateSpecVersions().CreateOrUpdateAsync(version, templateSpecVersionData)).Value; TemplateSpecVersion getTemplateSpecVersion = await templateSpec.GetTemplateSpecVersions().GetAsync(version); AssertValidTemplateSpecVersion(templateSpecVersion, getTemplateSpecVersion); Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await templateSpec.GetTemplateSpecVersions().GetAsync(null)); }
private static void AssertValidTemplateSpecVersion(TemplateSpecVersion model, TemplateSpecVersion getResult) { Assert.AreEqual(model.Data.Name, getResult.Data.Name); Assert.AreEqual(model.Data.Id, getResult.Data.Id); Assert.AreEqual(model.Data.ResourceType, getResult.Data.ResourceType); Assert.AreEqual(model.Data.Location, getResult.Data.Location); Assert.AreEqual(model.Data.Tags, getResult.Data.Tags); Assert.AreEqual(model.Data.Description, getResult.Data.Description); Assert.AreEqual(model.Data.LinkedTemplates.Count, getResult.Data.LinkedTemplates.Count); for (int i = 0; i < model.Data.LinkedTemplates.Count; ++i) { Assert.AreEqual(model.Data.LinkedTemplates[i].Path, getResult.Data.LinkedTemplates[i].Path); Assert.AreEqual(model.Data.LinkedTemplates[i].Template, getResult.Data.LinkedTemplates[i].Template); } Assert.AreEqual(model.Data.Metadata, getResult.Data.Metadata); Assert.AreEqual(model.Data.MainTemplate, getResult.Data.MainTemplate); Assert.AreEqual(model.Data.UiFormDefinition, getResult.Data.UiFormDefinition); }
/// <summary> /// Converts a template spec model from the Azure SDK to the powershell /// exposed template spec model. /// </summary> /// <param name="templateSpecVersion">The Azure SDK template spec model</param> /// <returns>The converted model or null if no model was specified</returns> internal static PSTemplateSpecVersion FromAzureSDKTemplateSpecVersion( TemplateSpecVersion templateSpecVersion) { if (templateSpecVersion == null) { return(null); } var psTemplateSpecVersion = new PSTemplateSpecVersion { CreationTime = templateSpecVersion.SystemData.CreatedAt, Id = templateSpecVersion.Id, LastModifiedTime = templateSpecVersion.SystemData.LastModifiedAt, Name = templateSpecVersion.Name, Description = templateSpecVersion.Description, Tags = templateSpecVersion.Tags == null ? new Dictionary <string, string>() : new Dictionary <string, string>(templateSpecVersion.Tags), // Note: Cast is redundant, but present for clarity reasons: Template = ((JToken)templateSpecVersion.Template).ToString() }; if (templateSpecVersion.Artifacts?.Any() == true) { foreach (TemplateSpecArtifact artifact in templateSpecVersion.Artifacts) { switch (artifact) { case TemplateSpecTemplateArtifact templateArtifact: psTemplateSpecVersion.Artifacts.Add( PSTemplateSpecTemplateArtifact.FromAzureSDKTemplateSpecTemplateArtifact(templateArtifact) ); break; default: throw new PSNotSupportedException( $"Template spec artifact type '${artifact.GetType().Name}' not supported by cmdlets." ); } } } return(psTemplateSpecVersion); }
public async Task Delete() { string rgName = Recording.GenerateAssetName("testRg-1-"); ResourceGroupData rgData = new ResourceGroupData(Location.WestUS2); var lro = await Client.DefaultSubscription.GetResourceGroups().CreateOrUpdateAsync(rgName, rgData); ResourceGroup rg = lro.Value; string templateSpecName = Recording.GenerateAssetName("templateSpec-C-"); TemplateSpecData templateSpecData = CreateTemplateSpecData(templateSpecName); TemplateSpec templateSpec = (await rg.GetTemplateSpecs().CreateOrUpdateAsync(templateSpecName, templateSpecData)).Value; const string version = "v1"; TemplateSpecVersionData templateSpecVersionData = CreateTemplateSpecVersionData(); TemplateSpecVersion templateSpecVersion = (await templateSpec.GetTemplateSpecVersions().CreateOrUpdateAsync(version, templateSpecVersionData)).Value; await templateSpecVersion.DeleteAsync(); var ex = Assert.ThrowsAsync <RequestFailedException>(async() => await templateSpecVersion.GetAsync()); Assert.AreEqual(404, ex.Status); }
public PSTemplateSpec CreateOrUpdateTemplateSpecVersion( string resourceGroupName, string templateSpecName, string templateSpecVersion, string location, PackagedTemplate packagedTemplate, string templateSpecDisplayName = null, string templateSpecDescription = null, string versionDescription = null) { var templateSpecModel = this.CreateOrUpdateTemplateSpecInternal( resourceGroupName, templateSpecName, location, templateSpecDisplayName, templateSpecDescription ); var existingTemplateSpecVersion = this.GetAzureSdkTemplateSpecVersion( resourceGroupName, templateSpecName, templateSpecVersion, throwIfNotExists: false ); var templateSpecVersionModel = new TemplateSpecVersion { Location = templateSpecModel.Location, Template = packagedTemplate.RootTemplate, Artifacts = packagedTemplate.Artifacts?.ToList(), Description = versionDescription ?? existingTemplateSpecVersion?.Description }; templateSpecVersionModel = TemplateSpecsClient.TemplateSpecVersions.CreateOrUpdate( resourceGroupName, templateSpecName, templateSpecVersion, templateSpecVersionModel ); return(new PSTemplateSpec(templateSpecModel, new[] { templateSpecVersionModel })); }
public async Task CreateOrUpdate() { Subscription subscription = await Client.GetDefaultSubscriptionAsync(); string rgName = Recording.GenerateAssetName("testRg-1-"); ResourceGroupData rgData = new ResourceGroupData(AzureLocation.WestUS2); var lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, rgName, rgData); ResourceGroup rg = lro.Value; string templateSpecName = Recording.GenerateAssetName("templateSpec-C-"); TemplateSpecData templateSpecData = CreateTemplateSpecData(templateSpecName); TemplateSpec templateSpec = (await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, templateSpecName, templateSpecData)).Value; const string version = "v1"; TemplateSpecVersionData templateSpecVersionData = CreateTemplateSpecVersionData(); TemplateSpecVersion templateSpecVersion = (await templateSpec.GetTemplateSpecVersions().CreateOrUpdateAsync(WaitUntil.Completed, version, templateSpecVersionData)).Value; Assert.AreEqual(version, templateSpecVersion.Data.Name); Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, null, templateSpecData)); Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetTemplateSpecs().CreateOrUpdateAsync(WaitUntil.Completed, templateSpecName, null)); }
public PSTemplateSpec CreateOrUpdateTemplateSpecVersion( string resourceGroupName, string templateSpecName, string templateSpecVersion, string location, PackagedTemplate packagedTemplate, object UIFormDefinition, string templateSpecDisplayName = null, string templateSpecDescription = null, string versionDescription = null, Hashtable templateSpecTags = null, Hashtable versionTags = null) { var templateSpecModel = this.CreateOrUpdateTemplateSpecInternal( resourceGroupName, templateSpecName, location, templateSpecDisplayName, templateSpecDescription, tags: templateSpecTags, onlyApplyTagsOnCreate: true // Don't update tags if the template spec already exists ); var existingTemplateSpecVersion = this.GetAzureSdkTemplateSpecVersion( resourceGroupName, templateSpecName, templateSpecVersion, throwIfNotExists: false ); var templateSpecVersionModel = new TemplateSpecVersion { Location = templateSpecModel.Location, MainTemplate = packagedTemplate.RootTemplate, LinkedTemplates = packagedTemplate.Artifacts?.ToList(), Description = versionDescription ?? existingTemplateSpecVersion?.Description, UiFormDefinition = UIFormDefinition }; // Handle our conditional tagging: // ------------------------------------------ if (versionTags != null) { // Explicit version tags provided. Use them: templateSpecVersionModel.Tags = TagsConversionHelper.CreateTagDictionary(versionTags, true); } else if (existingTemplateSpecVersion != null) { // No tags were provided. The template spec version already exists // ... keep the existing version's tags: templateSpecVersionModel.Tags = existingTemplateSpecVersion.Tags; } else { // No tags were provided. The template spec version does not already exist // ... inherit the tags present on the underlying template spec: templateSpecVersionModel.Tags = templateSpecModel.Tags; } // Perform the actual version create/update: // ------------------------------------------ templateSpecVersionModel = TemplateSpecsClient.TemplateSpecVersions.CreateOrUpdate( resourceGroupName, templateSpecName, templateSpecVersion, templateSpecVersionModel ); return(new PSTemplateSpec(templateSpecModel, new[] { templateSpecVersionModel })); }
public void CanCrudSimpleTemplateSpecVersion() { using (var context = MockContext.Start(this.GetType())) { var client = context.GetServiceClient <TemplateSpecsClient>(); var resourceGroupClient = context.GetServiceClient <ResourceManagementClient>(); // Create our test resource group: var resourceGroupName = $"{TestUtilities.GenerateName("TS-SDKTest-")}-RG"; var resourceGroup = resourceGroupClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup(TestLocation) ); try { // Create the template spec: var templateSpecName = $"{TestUtilities.GenerateName("TS-SDKTest-")}"; var templateSpecToCreate = new TemplateSpec { Location = TestLocation }; var createdTemplateSpec = client.TemplateSpecs.CreateOrUpdate( resourceGroupName, templateSpecName, templateSpecToCreate ); Assert.NotNull(createdTemplateSpec); // Now create a simple template spec version: var templateSpecVersionToCreate = new TemplateSpecVersion { Description = "My first version", Location = TestLocation, Template = JObject.Parse( File.ReadAllText( Path.Combine("ScenarioTests", "simple-storage-account.json") ) ) }; const string versionName = "v1"; var createdTemplateSpecVersion = client.TemplateSpecVersions.CreateOrUpdate( resourceGroupName, templateSpecName, "v1", templateSpecVersionToCreate ); Assert.NotNull(createdTemplateSpecVersion); // Validate user specified details: Assert.Equal(TestLocation, createdTemplateSpecVersion.Location); Assert.Equal(createdTemplateSpecVersion.Name, versionName); Assert.Equal(createdTemplateSpecVersion.Description, templateSpecVersionToCreate.Description); Assert.Equal(createdTemplateSpecVersion.Template?.ToString(), templateSpecVersionToCreate.Template.ToString()); // Validate readonly properties are present: Assert.NotNull(createdTemplateSpecVersion.Id); Assert.NotNull(createdTemplateSpecVersion.Type); Assert.NotNull(createdTemplateSpecVersion.SystemData?.CreatedAt); Assert.NotNull(createdTemplateSpecVersion.SystemData?.CreatedBy); Assert.NotNull(createdTemplateSpecVersion.SystemData?.CreatedByType); Assert.NotNull(createdTemplateSpecVersion.SystemData?.LastModifiedAt); Assert.NotNull(createdTemplateSpecVersion.SystemData?.LastModifiedBy); Assert.NotNull(createdTemplateSpecVersion.SystemData?.LastModifiedByType); // Make sure our object returned from GET is equal to the one which was returned // from the creation: var templateSpecVersionFromGet = client.TemplateSpecVersions.Get(resourceGroupName, templateSpecName, versionName); Assert.Equal( JsonConvert.SerializeObject(createdTemplateSpecVersion), JsonConvert.SerializeObject(templateSpecVersionFromGet) ); // Validate we can perform an update on the existing version: var templateSpecVersionUpdate = JsonConvert.DeserializeObject <TemplateSpecVersion>( JsonConvert.SerializeObject(templateSpecVersionToCreate) ); templateSpecVersionUpdate.Description = "This is an updated description"; var updatedTemplateSpecVersion = client.TemplateSpecVersions.CreateOrUpdate( resourceGroupName, templateSpecName, versionName, templateSpecVersionUpdate ); updatedTemplateSpecVersion.Description.Equals(templateSpecVersionUpdate.Description); // Validate we can get the version when listing versions on the template spec: var listVersionsResult = client.TemplateSpecVersions.List(resourceGroupName, templateSpecName); Assert.Equal(1, listVersionsResult?.Count()); var versionFromList = listVersionsResult.FirstOrDefault( tsv => tsv.Name.Equals(versionName) ); Assert.NotNull(versionFromList); // Now delete the template spec and make sure the version is no longer retrievable: client.TemplateSpecs.Delete(resourceGroupName, templateSpecName); Assert.ThrowsAny <Exception>( () => client.TemplateSpecVersions.Get(resourceGroupName, templateSpecName, versionName) ); } finally { resourceGroupClient.ResourceGroups.Delete(resourceGroupName); } } }
public PackagedTemplate(TemplateSpecVersion versionModel) { this.RootTemplate = (JObject)versionModel?.Template; this.Artifacts = versionModel?.Artifacts?.ToArray() ?? new TemplateSpecArtifact[0]; }
/// <summary> /// Creates or updates a Template Spec version. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='templateSpecName'> /// Name of the Template Spec. /// </param> /// <param name='templateSpecVersion'> /// The version of the Template Spec. /// </param> /// <param name='templateSpecVersionModel'> /// Template Spec Version supplied to the operation. /// </param> public static TemplateSpecVersion CreateOrUpdate(this ITemplateSpecVersionsOperations operations, string resourceGroupName, string templateSpecName, string templateSpecVersion, TemplateSpecVersion templateSpecVersionModel) { return(operations.CreateOrUpdateAsync(resourceGroupName, templateSpecName, templateSpecVersion, templateSpecVersionModel).GetAwaiter().GetResult()); }
/// <summary> /// Creates or updates a Template Spec version. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='templateSpecName'> /// Name of the Template Spec. /// </param> /// <param name='templateSpecVersion'> /// The version of the Template Spec. /// </param> /// <param name='templateSpecVersionModel'> /// Template Spec Version supplied to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <TemplateSpecVersion> CreateOrUpdateAsync(this ITemplateSpecVersionsOperations operations, string resourceGroupName, string templateSpecName, string templateSpecVersion, TemplateSpecVersion templateSpecVersionModel, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, templateSpecName, templateSpecVersion, templateSpecVersionModel, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }