private void AnalyseDefinedVars(AnalysisContext context) { ProjectResource project = OctopusRepository.Projects.FindByName(context.ProjectName); // Les librairies attachées au projet List <LibraryVariableSetResource> librarySets = OctopusRepository.LibraryVariableSets.FindMany(lib => project.IncludedLibraryVariableSetIds.Contains(lib.Id)); foreach (var libraryVariableSetResource in librarySets) { VariableSetResource variableSet = OctopusRepository.VariableSets.Get(libraryVariableSetResource.VariableSetId); variableSet.Variables.ToList().ForEach(v => { foreach (var envId in v.Scope.First().Value) { context.Result.AddDefinedVar(envId, v, VarOrigin.Lib); } }); } // Les vars attachées au projet OctopusRepository.VariableSets.Get(project.VariableSetId).Variables.ToList().ForEach(v => { foreach (var envId in v.Scope.First().Value) { context.Result.AddDefinedVar(envId, v, VarOrigin.AppVar); } }); }
void ImportVariableSets(VariableSetResource variableSet, ProjectResource importedProject, Dictionary <string, EnvironmentResource> environments, Dictionary <string, MachineResource> machines, Dictionary <ScopeField, List <ReferenceDataItem> > scopeValuesUsed) { Log.Debug("Importing the Projects Variable Set"); var existingVariableSet = Repository.VariableSets.Get(importedProject.VariableSetId); var variables = UpdateVariables(variableSet, environments, machines); existingVariableSet.Variables.Clear(); existingVariableSet.Variables.AddRange(variables); var scopeValues = UpdateScopeValues(environments, machines, scopeValuesUsed); existingVariableSet.ScopeValues.Actions.Clear(); existingVariableSet.ScopeValues.Actions.AddRange(scopeValues.Actions); existingVariableSet.ScopeValues.Environments.Clear(); existingVariableSet.ScopeValues.Environments.AddRange(scopeValues.Environments); existingVariableSet.ScopeValues.Machines.Clear(); existingVariableSet.ScopeValues.Machines.AddRange(scopeValues.Machines); existingVariableSet.ScopeValues.Roles.Clear(); existingVariableSet.ScopeValues.Roles.AddRange(scopeValues.Roles); existingVariableSet.ScopeValues.Machines.AddRange(scopeValues.Machines); Repository.VariableSets.Modify(existingVariableSet); }
async Task ImportVariableSets(VariableSetResource variableSet, ProjectResource importedProject, IDictionary <string, EnvironmentResource> environments, IDictionary <string, MachineResource> machines, IDictionary <string, ChannelResource> channels, IDictionary <ScopeField, List <ReferenceDataItem> > scopeValuesUsed) { Log.Debug("Importing the Projects Variable Set"); var existingVariableSet = await Repository.VariableSets.Get(importedProject.VariableSetId).ConfigureAwait(false); var variables = UpdateVariables(variableSet, environments, machines, channels); existingVariableSet.Variables.Clear(); existingVariableSet.Variables.AddRange(variables); var scopeValues = UpdateScopeValues(environments, machines, channels, scopeValuesUsed); existingVariableSet.ScopeValues.Actions.Clear(); existingVariableSet.ScopeValues.Actions.AddRange(scopeValues.Actions); existingVariableSet.ScopeValues.Environments.Clear(); existingVariableSet.ScopeValues.Environments.AddRange(scopeValues.Environments); existingVariableSet.ScopeValues.Machines.Clear(); existingVariableSet.ScopeValues.Machines.AddRange(scopeValues.Machines); existingVariableSet.ScopeValues.Roles.Clear(); existingVariableSet.ScopeValues.Roles.AddRange(scopeValues.Roles); existingVariableSet.ScopeValues.Machines.AddRange(scopeValues.Machines); await Repository.VariableSets.Modify(existingVariableSet).ConfigureAwait(false); }
IList <VariableResource> UpdateVariables(VariableSetResource variableSet, IDictionary <string, EnvironmentResource> environments, IDictionary <string, MachineResource> machines, IDictionary <string, ChannelResource> channels) { var variables = variableSet.Variables; foreach (var variable in variables) { if (variable.IsSensitive) { Log.Warning("{Variable} is a sensitive variable and it's value will be reset to a blank string, once the import has completed you will have to update it's value from the UI", variable.Name); variable.Value = string.Empty; } foreach (var scopeValue in variable.Scope) { switch (scopeValue.Key) { case ScopeField.Environment: Log.Debug("Updating the Environment IDs of the Variables scope"); var oldEnvironmentIds = scopeValue.Value; var newEnvironmentIds = new List <string>(); foreach (var oldEnvironmentId in oldEnvironmentIds) { newEnvironmentIds.Add(environments[oldEnvironmentId].Id); } scopeValue.Value.Clear(); scopeValue.Value.AddRange(newEnvironmentIds); break; case ScopeField.Machine: Log.Debug("Updating the Machine IDs of the Variables scope"); var oldMachineIds = scopeValue.Value; var newMachineIds = new List <string>(); foreach (var oldMachineId in oldMachineIds) { newMachineIds.Add(machines[oldMachineId].Id); } scopeValue.Value.Clear(); scopeValue.Value.AddRange(newMachineIds); break; case ScopeField.Channel: Log.Debug("Updating the Channel IDs of the Variables scope"); var oldChannelIds = scopeValue.Value; var newChannelIds = new List <string>(); foreach (var oldChannelId in oldChannelIds) { newChannelIds.Add(channels[oldChannelId].Id); } scopeValue.Value.Clear(); scopeValue.Value.AddRange(newChannelIds); break; } } } return(variables); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(CopyStep)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create project var project = new ProjectResource { Name = "Octopus", Description = "Test Source", DeploymentProcessId = "deploymentprocesses-1", VariableSetId = "variablesets-1", }; // Create projects octoRepo.Setup(o => o.Projects.FindByName("Octopus", It.IsAny <string>(), It.IsAny <object>())).Returns(project); octoRepo.Setup(o => o.Projects.FindByName("Gibberish", It.IsAny <string>(), It.IsAny <object>())).Returns((ProjectResource)null); // Create deployment process var action = new DeploymentActionResource { Name = "NuGet", ActionType = "NuGet" }; action.Environments.Add("environments-1"); action.Properties.Add("Something", "Value"); action.Properties.Add("SomethingElse", new PropertyValueResource("Secret", true)); var step = new DeploymentStepResource { Id = "deploymentsteps-1", Name = "Website" }; step.Actions.Add(action); _process = new DeploymentProcessResource(); _process.Steps.Add(step); octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsIn(new[] { "deploymentprocesses-1" }))).Returns(_process); octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsIn(new[] { "deploymentprocesses-2" }))).Returns(new DeploymentProcessResource()); // Create variable set var variable = new VariableResource { Name = "Name", Value = "Value" }; variable.Scope.Add(ScopeField.Action, "DeploymentsActions-1"); variable.Scope.Add(ScopeField.Environment, "Environments-1"); var variableSet = new VariableSetResource(); variableSet.Variables.Add(variable); octoRepo.Setup(o => o.VariableSets.Get(It.IsIn(new[] { "variablesets-1" }))).Returns(variableSet); octoRepo.Setup(o => o.VariableSets.Get(It.IsIn(new[] { "variablesets-2" }))).Returns(new VariableSetResource()); }
/// <summary> /// BeginProcessing /// </summary> protected override void BeginProcessing() { _octopus = Session.RetrieveSession(this); var project = LoadProject(); _variableSet = _octopus.VariableSets.Get(project.Link("Variables")); WriteDebug("Found variable set" + _variableSet.Id); if (Steps != null) { LoadDeploymentProcess(project); } }
/// <summary> /// BeginProcessing /// </summary> protected override void BeginProcessing() { _octopus = Session.RetrieveSession(this); // Find the project that owns the variables we want to edit var project = _octopus.Projects.FindByName(Project); if (project == null) { throw new Exception(string.Format("Project '{0}' was not found.", Project)); } // Get the variables for editing _variableSet = _octopus.VariableSets.Get(project.Link("Variables")); }
/// <summary> /// BeginProcessing /// </summary> protected override void BeginProcessing() { _octopus = Session.RetrieveSession(this); var libraryVariableSet = _octopus.LibraryVariableSets.FindOne( v => v.Name.Equals(VariableSet, StringComparison.InvariantCultureIgnoreCase)); if (libraryVariableSet == null) { throw new Exception(string.Format("Library variable set '{0}' was not found.", VariableSet)); } _variableSet = _octopus.VariableSets.Get(libraryVariableSet.Link("Variables")); WriteDebug("Found variable set" + _variableSet.Id); }
public GetVariableSetTests() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetVariableSet)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a library variable set const string vsId = "/api/variables/variableset-LibraryVariableSets-1"; var libraryResources = new List <LibraryVariableSetResource> { new LibraryVariableSetResource { Id = "LibraryVariableSets-1", Name = "Octopus" }, new LibraryVariableSetResource { Id = "LibraryVariableSets-2", Name = "Deploy" }, new LibraryVariableSetResource { Id = "LibraryVariableSets-3", Name = "Automation" } }; octoRepo.Setup(o => o.LibraryVariableSets.FindAll(null, null)).Returns(libraryResources); // Create a variableset var variableRepo = new Mock <IVariableSetRepository>(); var vsResource = new VariableSetResource { Variables = new List <VariableResource> { new VariableResource { Name = "Octopus" }, new VariableResource { Name = "Deploy" }, new VariableResource { Name = "Automation" }, } }; variableRepo.Setup(v => v.Get(vsId)).Returns(vsResource); octoRepo.Setup(o => o.VariableSets).Returns(variableRepo.Object); }
private Dictionary <ScopeField, ScopeValue> GetVariableScopes(VariableSetResource variableSet, Dictionary <ScopeField, string> scopes) { var variableScopes = new Dictionary <ScopeField, ScopeValue>(); foreach (var scopeField in scopes.Keys) { var scopeValues = GetScopeValues(variableSet.ScopeValues, scopeField); var scopeValueName = scopes[scopeField]; var scopeValue = scopeValues.FirstOrDefault(item => item.Name == scopeValueName); if (scopeValue == null) { continue; } variableScopes.Add(scopeField, new ScopeValue(scopeValue.Id)); } return(variableScopes); }
/// <summary> /// BeginProcessing /// </summary> protected override void BeginProcessing() { _octopus = Session.RetrieveSession(this); WriteDebug("Got connection"); // Find the project that owns the variables we want to edit var project = _octopus.Projects.FindByName(Project); if (project == null) { const string msg = "Project '{0}' was not found."; throw new Exception(string.Format(msg, Project)); } WriteDebug("Found project" + project.Id); // Get the variables for editing _variableSet = _octopus.VariableSets.Get(project.Link("Variables")); WriteDebug("Found variable set" + _variableSet.Id); }
public async Task EmptyVariablesShoudBePassedToModify([Frozen] Mock <IOctopusAsyncRepository> mockRepo, [Frozen] Mock <IVariableSetRepository> mockVar, [Frozen] Mock <ILibraryVariableSetRepository> mockLib, LibraryVariableSetResource libResource, VariableSetResource varResource, LibraryManager sut) { mockLib.Setup(m => m.FindByName(It.Is <string>(s => s.Equals(libResource.Name)), It.IsAny <string>(), It.IsAny <string>())) .Returns(Task.FromResult(libResource)); mockVar.Setup(m => m.Get(It.Is <string>(s => s.Equals(varResource.Id)))) .Returns(Task.FromResult(varResource)); mockRepo.Setup(m => m.VariableSets).Returns(mockVar.Object); var expected = varResource.Variables.Count; var actual = await sut.ClearLibrarySet(libResource.Name).ConfigureAwait(false); Assert.Equal(expected, actual); mockVar.Verify(m => m.Modify(It.Is <VariableSetResource>(v => v.Variables.Count == 0)), Times.Once); }
private static ScopeSpecification CreateScopeSpesification(OctoVariable variable, VariableSetResource variableSet) { var scopeSpecifiaciton = new ScopeSpecification(); variable.Scopes.ForEach(scope => { ScopeField scopeName = FindScopeName(scope); List <ReferenceDataItem> referenceDataItems = FindScopeValue(scopeName, variableSet); List <string> scopeValues = referenceDataItems.Join(scope.Values, refDataItem => refDataItem.Name, selectedScope => selectedScope, (item, s) => item.Id) .ToList(); if (!scopeValues.Any()) { throw new CakeException($"({string.Join(",", scope.Values)}) value(s) can not be found on ({scope.Name}) scope."); } var value = new ScopeValue(scopeValues.First(), scopeValues.Skip(1).ToArray()); scopeSpecifiaciton.Add(scopeName, value); }); return(scopeSpecifiaciton); }
private static List <ReferenceDataItem> FindScopeValue(ScopeField scopeField, VariableSetResource variableSet) { List <ReferenceDataItem> referenceDataItem; switch (scopeField) { case ScopeField.Environment: referenceDataItem = variableSet.ScopeValues.Environments; break; case ScopeField.Role: referenceDataItem = variableSet.ScopeValues.Roles; break; case ScopeField.Machine: referenceDataItem = variableSet.ScopeValues.Machines; break; case ScopeField.Action: referenceDataItem = variableSet.ScopeValues.Actions; break; default: throw new ArgumentOutOfRangeException(nameof(scopeField)); } return(referenceDataItem); }
private static IReadOnlyCollection <VariableResource> FilterVariables(IEnumerable <string> environments, VariableSetResource variables) => variables.Variables.Where(x => !x.Scope.ContainsKey(ScopeField.Environment) || x.Scope[ScopeField.Environment].Any(environments.Contains)).ToList();
public static void OctoImportVariables(this ICakeContext context, string octopusServerEndpoint, string octopusProjectName, string octopusApiKey, IEnumerable <OctoVariable> variables, bool clearAllNonSensitiveExistingVariables = false) { try { IOctopusAsyncClient client = new OctopusClientFactory().CreateAsyncClient(new OctopusServerEndpoint(octopusServerEndpoint, octopusApiKey)).Result; var octopus = new OctopusAsyncRepository(client); ProjectResource project = octopus.Projects.FindByName(octopusProjectName).Result; VariableSetResource variableSet = octopus.VariableSets.Get(project.Link("Variables")).Result; if (clearAllNonSensitiveExistingVariables) { context.Log.Information($"Deleting all nonsensitive variables..."); List <VariableResource> sensitiveVariables = variableSet.Variables.Where(variable => variable.IsSensitive).ToList(); variableSet.Variables.Clear(); sensitiveVariables.ForEach(sensitiveVariable => { variableSet.Variables.Add(sensitiveVariable); }); context.Log.Information($"Deleting operation finished."); } foreach (OctoVariable variable in variables) { var newVariable = new VariableResource { Name = variable.Name, Value = variable.Value, IsSensitive = variable.IsSensitive, Type = variable.IsSensitive ? VariableType.Sensitive : VariableType.String, IsEditable = variable.IsEditable, Scope = CreateScopeSpesification(variable, variableSet) }; string scopeNames = CreateScopeInformationsForLogging(variable); VariableResource existingVariable = variableSet.Variables.FirstOrDefault(x => x.Name == variable.Name && x.Scope.Equals(newVariable.Scope)); if (existingVariable != null) { context.Log.Information($"Variable: ({variable.Name}), Scopes:({scopeNames}) already exists in octopus, trying to update..."); variableSet.AddOrUpdateVariableValue(existingVariable.Name, newVariable.Value, newVariable.Scope, newVariable.IsSensitive); context.Log.Information($"Variable: ({variable.Name}), Scopes:({scopeNames}) updated successfully..."); } else { context.Log.Information($"New Variable: ({variable.Name}), Scopes:({scopeNames}) detected, trying to add..."); variableSet.Variables.Add(newVariable); context.Log.Information($"New Variable: ({variable.Name}), Scopes:({scopeNames}) added successfully..."); } } octopus.VariableSets.Modify(variableSet).Wait(); octopus.VariableSets.Refresh(variableSet).Wait(); context.Log.Information($"Variables are all successfully set."); } catch (Exception exception) { throw new CakeException(exception.Message, exception.InnerException); } }
private void AddVariableSet(IDictionary <string, SortedSet <VariableResource> > variables, VariableSetResource variableSet, Dictionary <ScopeField, string> scopes) { var variableScopes = GetVariableScopes(variableSet, scopes); foreach (var variable in variableSet.Variables) { var variableName = variable.Name; if (variable.IsSensitive) { continue; } if (!variable.Scope.IsApplicableTo(variableScopes)) { continue; } if (!variables.ContainsKey(variableName)) { variables[variableName] = new SortedSet <VariableResource>(new VariableResourceScopeRankComparer()); } variables[variableName].Add(variable); } }
public static VariableSetResource UpdateWith(this VariableSetResource resource, IVariableSet model, IOctopusRepository repository, DeploymentProcessResource deploymentProcess) { resource.Variables = model.Variables.Select(v => new VariableResource().UpdateWith(v, repository, deploymentProcess)).ToList(); return(resource); }
public static IEnumerable <Variable> ToModel(this VariableSetResource resource, DeploymentProcessResource deploymentProcessResource, IOctopusRepository repository) { return(resource.Variables.Select(v => v.ToModel(deploymentProcessResource, repository))); }
private List <string> GetComponentDependancies(ComponentFilter componentFilter, VariableSetResource projectVariables, string releaseId) { var componentDependanciesVariables = projectVariables.Variables .Where(x => x.Name == ComponentDependanciesVariableName && !string.IsNullOrEmpty(x.Value)).ToList(); try { return(componentDependanciesVariables .SelectMany(x => JsonConvert.DeserializeObject <string[]>(x.Value)) .Where(x => componentFilter == null || componentFilter.Match(x)) .Where(x => GetProjectByName(x)?.IsDisabled == false) .ToList()); } catch { var releaseUri = string.Format("/app#/releases/{0}", releaseId); throw new Exception(string.Format("The variable {0} is not a valid json string array. Please update at {1}\r\nCurrent value:\r\n{2}", componentDependanciesVariables, releaseUri, componentDependanciesVariables.First().Value)); } }
public static async Task <VariableSetResource> UpdateWith(this VariableSetResource resource, IVariableSet model, IOctopusAsyncRepository repository, DeploymentProcessResource deploymentProcess, ProjectResource project) { resource.Variables = (await Task.WhenAll(model.Variables.Select(v => new VariableResource().UpdateWith(v, repository, deploymentProcess, project)))).ToList(); return(resource); }
public static async Task <IEnumerable <Variable> > ToModel(this VariableSetResource resource, DeploymentProcessResource deploymentProcessResource, IOctopusAsyncRepository repository) { return(await Task.WhenAll(resource.Variables.Select(v => v.ToModel(deploymentProcessResource, repository)))); }
/// <summary> /// Replace's a Project's VariableSet. /// </summary> /// <param name="octRepository">The repository to call against.</param> /// <param name="project">Project to gather from.</param> /// <param name="variableSet">VariableSet that will be entered.</param> public static void ReplaceVariablesInProjectVariableSet(OctopusRepository octRepository, ProjectResource project, VariableSetResource variableSet) { var newVariableList = new List <VariableResource>(); foreach (var variable in variableSet.Variables) { var variableResource = new VariableResource(); variableResource.IsEditable = variable.IsEditable; variableResource.IsSensitive = variable.IsSensitive; variableResource.Name = variable.Name; variableResource.Prompt = variable.Prompt; variableResource.Scope = variable.Scope; variableResource.Value = variable.Value; newVariableList.Add(variableResource); } var currentProjectVariables = GetVariableSetFromProject(octRepository, project); currentProjectVariables.Variables = newVariableList; octRepository.VariableSets.Modify(currentProjectVariables); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(CopyProject)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a project group var groupResource = new ProjectGroupResource { Name = "Octopus", Id = "projectgroups-1" }; octoRepo.Setup(o => o.ProjectGroups.FindByName("Octopus")).Returns(groupResource); octoRepo.Setup(o => o.ProjectGroups.FindByName("Gibberish")).Returns((ProjectGroupResource)null); // Create project var project = new ProjectResource { Name = "Source", Description = "Test Source", DeploymentProcessId = "deploymentprocesses-1", VariableSetId = "variablesets-1", DefaultToSkipIfAlreadyInstalled = true, IncludedLibraryVariableSetIds = new List <string> { "libraryvariablesets-1" }, VersioningStrategy = new VersioningStrategyResource(), AutoCreateRelease = false, ReleaseCreationStrategy = new ReleaseCreationStrategyResource(), IsDisabled = false, LifecycleId = "lifecycle-1" }; // Create projects _projects.Clear(); _projects.Add(project); octoRepo.Setup(o => o.Projects.FindByName("Source")).Returns(project); octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource)null); octoRepo.Setup(o => o.Projects.Create(It.IsAny <ProjectResource>())).Returns( delegate(ProjectResource p) { p.VariableSetId = "variablesets-2"; p.DeploymentProcessId = "deploymentprocesses-2"; _projects.Add(p); return(p); } ); // Create deployment process var action = new DeploymentActionResource { Name = "Action" }; action.Environments.Add("environments-1"); var step = new DeploymentStepResource { Id = "deploymentsteps-1", Name = "Database" }; step.Actions.Add(action); var process = new DeploymentProcessResource(); process.Steps.Add(step); octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsIn(new[] { "deploymentprocesses-1" }))).Returns(process); _copyProcess = new DeploymentProcessResource(); octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsIn(new[] { "deploymentprocesses-2" }))).Returns(_copyProcess); // Create variable set var variable = new VariableResource { Name = "Name", Value = "Value" }; variable.Scope.Add(ScopeField.Action, "deploymentsactions-1"); variable.Scope.Add(ScopeField.Environment, "environments-1"); var sourceVariables = new VariableSetResource(); sourceVariables.Variables.Add(variable); octoRepo.Setup(o => o.VariableSets.Get(It.IsIn(new[] { "variablesets-1" }))).Returns(sourceVariables); _copyVariables = new VariableSetResource(); octoRepo.Setup(o => o.VariableSets.Get(It.IsIn(new[] { "variablesets-2" }))).Returns(_copyVariables); }
public void Init() { _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetVariable)); var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable); // Create a Project var projectRepo = new Mock <IProjectRepository>(); const string pVsId = "/api/variables/variableset-projects-1"; var projectResource = new ProjectResource { Name = "Octopus", Links = new LinkCollection { { "Variables", new Href(pVsId) } } }; projectRepo.Setup(p => p.FindByName("Octopus")).Returns(projectResource); octoRepo.Setup(o => o.Projects).Returns(projectRepo.Object); // Create a library variable set const string vsId = "/api/variables/variableset-LibraryVariableSets-1"; var libraryResources = new List <LibraryVariableSetResource> { new LibraryVariableSetResource { Id = "LibraryVariableSets-1", Name = "Octopus", Links = new LinkCollection { { "Variables", new Href("/api/variables/variableset-LibraryVariableSets-1") } } }, new LibraryVariableSetResource { Id = "LibraryVariableSets-2", Name = "Deploy", } }; // Allow the FindOne predicate to operate on the collection octoRepo.Setup(o => o.LibraryVariableSets.FindOne(It.IsAny <Func <LibraryVariableSetResource, bool> >())) .Returns( (Func <LibraryVariableSetResource, bool> f) => (from l in libraryResources where f(l) select l).FirstOrDefault()); // Create a variableset var variableRepo = new Mock <IVariableSetRepository>(); var vsResource = new VariableSetResource { Variables = new List <VariableResource> { new VariableResource { Name = "Octopus" }, new VariableResource { Name = "Deploy", Value = "To Production" }, new VariableResource { Name = "Automation" }, } }; variableRepo.Setup(v => v.Get(pVsId)).Returns(vsResource); variableRepo.Setup(v => v.Get(vsId)).Returns(vsResource); octoRepo.Setup(o => o.VariableSets).Returns(variableRepo.Object); }