Exemple #1
0
        private void FillProcessVariables(AnalysisContext context)
        {
            ProjectResource project = this.OctopusRepository.Projects.FindByName(context.ProjectName);

            DeploymentProcessResource deployementProcess = OctopusRepository.DeploymentProcesses.Get(project.DeploymentProcessId);

            deployementProcess.Steps.ToList().ForEach(step =>
            {
                step.Actions.ToList().ForEach(action =>
                {
                    if (action.Properties.Any())
                    {
                        action.Properties.Values.Where(p => Regex.IsMatch(p.Value, varPattern)).ToList().ForEach(p =>
                        {
                            foreach (Match match in Regex.Matches(p.Value, varPattern))
                            {
                                context.Result.AddToUsedVar(match.Value, VarUsage.ActionProperty, "on action " + action.Name);
                            }
                        });
                    }
                });

                step.Properties.Values.Where(p => Regex.IsMatch(p.Value, varPattern)).ToList().ForEach(p =>
                {
                    foreach (Match match in Regex.Matches(p.Value, varPattern))
                    {
                        context.Result.AddToUsedVar(match.Value, VarUsage.StepProperty, "on step " + step.Name);
                    }
                });
            });
        }
Exemple #2
0
        /// <summary>
        /// BeginProcessing
        /// </summary>
        protected override void BeginProcessing()
        {
            _octopus = Session.RetrieveSession(this);

            // Find the project that owns the variables we want to get
            var project = _octopus.Projects.FindByName(Project);

            if (project == null)
            {
                const string msg = "Project '{0}' was not found.";
                throw new Exception(string.Format(msg, Project));
            }

            var id = project.DeploymentProcessId;

            _deploymentProcess = _octopus.DeploymentProcesses.Get(id);

            var steps = from s in _deploymentProcess.Steps
                        where s.Name.Equals(Name, StringComparison.InvariantCultureIgnoreCase)
                        select s;

            _step = steps.FirstOrDefault();

            if (_step == null)
            {
                throw new Exception(string.Format("Step with name '{0}' was not found.", Name));
            }
        }
Exemple #3
0
        public void Init()
        {
            _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetAction));

            var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable);

            // Create a project
            var projectResource = new ProjectResource {
                Name = "Octopus"
            };

            octoRepo.Setup(o => o.Projects.FindByName("Octopus")).Returns(projectResource);

            // Create a deployment process
            var stepResource = new DeploymentStepResource();

            stepResource.Actions.Add(new DeploymentActionResource {
                Name = "Do Stuff", Id = "Globally unique identifier"
            });
            stepResource.Actions.Add(new DeploymentActionResource {
                Name = "Do Other Stuff", Id = "Universally unique identifier"
            });

            var dpResource = new DeploymentProcessResource();

            dpResource.Steps.Add(stepResource);

            var dpRepo = new Mock <IDeploymentProcessRepository>();

            dpRepo.Setup(d => d.Get(It.IsAny <string>())).Returns(dpResource);

            octoRepo.Setup(o => o.DeploymentProcesses).Returns(dpRepo.Object);
        }
        private void LoadDeploymentProcess(ProjectResource project)
        {
            var id = project.DeploymentProcessId;

            _deploymentProcess = _octopus.DeploymentProcesses.Get(id);

            WriteDebug("Loaded the deployment process");
        }
Exemple #5
0
        async Task <DeploymentProcessResource> ImportDeploymentProcess(DeploymentProcessResource deploymentProcess,
                                                                       ProjectResource importedProject,
                                                                       IDictionary <string, EnvironmentResource> environments,
                                                                       IDictionary <string, WorkerPoolResource> workerPools,
                                                                       IDictionary <string, FeedResource> nugetFeeds,
                                                                       IDictionary <string, ActionTemplateResource> actionTemplates)
        {
            Log.Debug("Importing the Projects Deployment Process");
            var existingDeploymentProcess = await Repository.DeploymentProcesses.Get(importedProject.DeploymentProcessId).ConfigureAwait(false);

            var steps = deploymentProcess.Steps;

            foreach (var step in steps)
            {
                foreach (var action in step.Actions)
                {
                    if (action.Properties.ContainsKey("Octopus.Action.Package.NuGetFeedId"))
                    {
                        Log.Debug("Updating ID of NuGet Feed");
                        var nugetFeedId = action.Properties["Octopus.Action.Package.NuGetFeedId"];
                        action.Properties["Octopus.Action.Package.NuGetFeedId"] = nugetFeeds[nugetFeedId.Value].Id;
                    }

                    if (action.Properties.ContainsKey("Octopus.Action.Template.Id"))
                    {
                        Log.Debug("Updating ID and version of Action Template");
                        var templateId = action.Properties["Octopus.Action.Template.Id"];
                        var template   = actionTemplates[templateId.Value];
                        action.Properties["Octopus.Action.Template.Id"]      = template.Id;
                        action.Properties["Octopus.Action.Template.Version"] = template.Version.ToString(CultureInfo.InvariantCulture);
                    }

                    var oldEnvironmentIds = action.Environments;
                    var newEnvironmentIds = new List <string>();
                    Log.Debug("Updating IDs of Environments");
                    foreach (var oldEnvironmentId in oldEnvironmentIds)
                    {
                        newEnvironmentIds.Add(environments[oldEnvironmentId].Id);
                    }
                    action.Environments.Clear();
                    action.Environments.AddRange(newEnvironmentIds);

                    if (!string.IsNullOrWhiteSpace(action.WorkerPoolId))
                    {
                        Log.Debug("Updating ID of Worker Pool");
                        action.WorkerPoolId = workerPools[action.WorkerPoolId].Id;
                    }

                    // Make sure source channels are clear, will be added later
                    action.Channels.Clear();
                }
            }

            existingDeploymentProcess.Steps.Clear();
            existingDeploymentProcess.Steps.AddRange(steps);

            return(await Repository.DeploymentProcesses.Modify(existingDeploymentProcess).ConfigureAwait(false));
        }
 public static Variable ToModel(this VariableResource resource, DeploymentProcessResource deploymentProcessResource, IOctopusRepository repository)
 {
     return(new Variable(
                resource.Name,
                resource.IsEditable,
                resource.IsSensitive,
                resource.Value,
                resource.Scope.ToModel(deploymentProcessResource, repository),
                resource.Prompt?.ToModel()));
 }
Exemple #7
0
        public static DeploymentProcessResource UpdateWith(this DeploymentProcessResource resource, DeploymentProcess model, IOctopusRepository repository)
        {
            resource.Steps.Clear();
            foreach (var step in model.DeploymentSteps.Select(s => new DeploymentStepResource().UpdateWith(s, repository)))
            {
                resource.Steps.Add(step);
            }

            return(resource);
        }
Exemple #8
0
        void ImportDeploymentProcess(DeploymentProcessResource deploymentProcess,
                                     ProjectResource importedProject,
                                     IDictionary <string, EnvironmentResource> environments,
                                     IDictionary <string, FeedResource> nugetFeeds,
                                     IDictionary <string, ActionTemplateResource> actionTemplates,
                                     IDictionary <string, ChannelResource> channels)
        {
            Log.Debug("Importing the Projects Deployment Process");
            var existingDeploymentProcess = Repository.DeploymentProcesses.Get(importedProject.DeploymentProcessId);
            var steps = deploymentProcess.Steps;

            foreach (var step in steps)
            {
                foreach (var action in step.Actions)
                {
                    if (action.Properties.ContainsKey("Octopus.Action.Package.NuGetFeedId"))
                    {
                        Log.Debug("Updating ID of NuGet Feed");
                        var nugetFeedId = action.Properties["Octopus.Action.Package.NuGetFeedId"];
                        action.Properties["Octopus.Action.Package.NuGetFeedId"] = nugetFeeds[nugetFeedId.Value].Id;
                    }
                    if (action.Properties.ContainsKey("Octopus.Action.Template.Id"))
                    {
                        Log.Debug("Updating ID and version of Action Template");
                        var templateId = action.Properties["Octopus.Action.Template.Id"];
                        var template   = actionTemplates[templateId.Value];
                        action.Properties["Octopus.Action.Template.Id"]      = template.Id;
                        action.Properties["Octopus.Action.Template.Version"] = template.Version.ToString(CultureInfo.InvariantCulture);
                    }
                    var oldEnvironmentIds = action.Environments;
                    var newEnvironmentIds = new List <string>();
                    Log.Debug("Updating IDs of Environments");
                    foreach (var oldEnvironmentId in oldEnvironmentIds)
                    {
                        newEnvironmentIds.Add(environments[oldEnvironmentId].Id);
                    }
                    action.Environments.Clear();
                    action.Environments.AddRange(newEnvironmentIds);

                    var oldChannelIds = action.Channels;
                    var newChannelIds = new List <string>();
                    Log.Debug("Updating IDs of Channels");
                    foreach (var oldChannelId in oldChannelIds)
                    {
                        newChannelIds.Add(channels[oldChannelId].Id);
                    }
                    action.Channels.Clear();
                    action.Channels.AddRange(newChannelIds);
                }
            }
            existingDeploymentProcess.Steps.Clear();
            existingDeploymentProcess.Steps.AddRange(steps);

            Repository.DeploymentProcesses.Modify(existingDeploymentProcess);
        }
        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());
        }
 async Task MapChannelsToAction(DeploymentProcessResource importedDeploymentProcess, IDictionary <string, ChannelResource> importedChannels, IDictionary <string, ReferenceCollection> oldActionChannels)
 {
     foreach (var step in importedDeploymentProcess.Steps)
     {
         foreach (var action in step.Actions)
         {
             Log.Debug("Setting action channels");
             action.Channels.AddRange(oldActionChannels[action.Id].Select(oldChannelId => importedChannels[oldChannelId].Id));
         }
     }
     await Repository.DeploymentProcesses.Modify(importedDeploymentProcess).ConfigureAwait(false);
 }
        public static Variable ToModel(this VariableResource resource, DeploymentProcessResource deploymentProcessResource, ProjectResource projectResource, IOctopusRepository repository)
        {
            Logger.Trace($"Converting variable {resource.Name} to model...");

            return(new Variable(
                       resource.Name,
                       resource.IsEditable,
                       resource.IsSensitive,
                       resource.Value,
                       resource.Scope.ToModel(deploymentProcessResource, projectResource, repository),
                       resource.Prompt?.ToModel()));
        }
Exemple #12
0
        private static DeploymentActionResource GetDeploymentAction(DeploymentProcessResource deploymentProcess, Func <DeploymentActionResource, string> identifierExtractor, string identifier, string identifierType)
        {
            if (deploymentProcess == null)
            {
                throw new InvalidOperationException("Unable to retrieve deployment action if no deployment process is specified");
            }
            var result = deploymentProcess.Steps.SelectMany(s => s.Actions).SingleOrDefault(a => identifierExtractor(a) == identifier);

            if (result == null)
            {
                throw new KeyNotFoundException($"{nameof(DeploymentActionResource)} with {identifierType.ToLowerInvariant()} '{identifier}' not found.");
            }
            return(result);
        }
Exemple #13
0
        public void Init()
        {
            _ps = Utilities.CreatePowerShell(CmdletName, typeof(AddLibraryVariable));
            var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable);

            _variableSet.Variables.Clear();

            var lib = new LibraryVariableSetResource {
                Name = "Octopus"
            };
            var libs = new List <LibraryVariableSetResource> {
                lib
            };

            lib.Links.Add("Variables", "variablesets-1");
            octoRepo.Setup(o => o.LibraryVariableSets.FindOne(It.IsAny <Func <LibraryVariableSetResource, bool> >()))
            .Returns(
                (Func <LibraryVariableSetResource, bool> f) =>
                (from l in libs where f(l) select l).FirstOrDefault());

            octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource)null);

            octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet);

            var process = new DeploymentProcessResource();

            process.Steps.Add(new DeploymentStepResource {
                Name = "Website", Id = "Step-1"
            });
            octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process);

            var envs = new List <EnvironmentResource>
            {
                new EnvironmentResource {
                    Id = "Environments-1", Name = "DEV"
                }
            };

            octoRepo.Setup(o => o.Environments.FindByNames(new[] { "DEV" })).Returns(envs);
            var machines = new List <MachineResource>
            {
                new MachineResource {
                    Id = "Machines-1", Name = "web-01"
                }
            };

            octoRepo.Setup(o => o.Machines.FindByNames(new[] { "web-01" })).Returns(machines);
        }
        public DeploymentProcessResource Modify(ProjectResource projectResource, DeploymentProcessResource resource, string commitMessage = null)
        {
            if (!projectResource.IsVersionControlled)
            {
                return(client.Update(projectResource.Link("DeploymentProcess"), resource));
            }

            var commitResource = new CommitResource <DeploymentProcessResource>
            {
                Resource      = resource,
                CommitMessage = commitMessage
            };

            client.Put(resource.Link("Self"), commitResource);
            return(client.Get <DeploymentProcessResource>(resource.Link("Self")));
        }
        /// <summary>
        /// BeginProcessing
        /// </summary>
        protected override void BeginProcessing()
        {
            _octopus = Session.RetrieveSession(this);

            // Find the project that owns the variables we want to get
            var project = _octopus.Projects.FindByName(Project);

            if (project == null)
            {
                const string msg = "Project '{0}' was not found.";
                throw new Exception(string.Format(msg, Project));
            }

            var id = project.DeploymentProcessId;

            _deploymentProcess = _octopus.DeploymentProcesses.Get(id);
        }
Exemple #16
0
 public ReleasePlan(ProjectResource project,
                    ChannelResource channel,
                    ReleaseTemplateResource releaseTemplate,
                    DeploymentProcessResource deploymentProcess,
                    IPackageVersionResolver versionResolver)
 {
     Project         = project;
     Channel         = channel;
     ReleaseTemplate = releaseTemplate;
     scriptSteps     = deploymentProcess.Steps
                       .SelectMany(s => s.Actions)
                       .Select(a => new
     {
         StepName  = a.Name,
         PackageId = a.Properties.ContainsKey("Octopus.Action.Package.PackageId")
                 ? a.Properties["Octopus.Action.Package.PackageId"].Value
                 : string.Empty,
         FeedId = a.Properties.ContainsKey("Octopus.Action.Package.FeedId")
                 ? a.Properties["Octopus.Action.Package.FeedId"].Value
                 : string.Empty,
         a.IsDisabled,
         a.Channels
     })
                       .Where(x => string.IsNullOrEmpty(x.PackageId) && x.IsDisabled == false) // only consider enabled script steps
                       .Where(a => !a.Channels.Any() || a.Channels.Contains(channel.Id))       // only include actions without channel scope or with a matchign channel scope
                       .Select(x =>
                               new ReleasePlanItem(x.StepName,
                                                   null,
                                                   null,
                                                   null,
                                                   true,
                                                   null)
     {
         IsDisabled = x.IsDisabled
     })
                       .ToArray();
     packageSteps = releaseTemplate.Packages.Select(
         p => new ReleasePlanItem(
             p.ActionName,
             p.PackageReferenceName,
             p.PackageId,
             p.FeedId,
             p.IsResolvable,
             versionResolver.ResolveVersion(p.ActionName, p.PackageId, p.PackageReferenceName)))
                    .ToArray();
 }
Exemple #17
0
        public AddVariableTests()
        {
            _ps = Utilities.CreatePowerShell(CmdletName, typeof(AddVariable));
            var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable);

            _variableSet.Variables.Clear();

            var project = new ProjectResource {
                DeploymentProcessId = "deploymentprocesses-1"
            };

            project.Links.Add("Variables", "variablesets-1");
            octoRepo.Setup(o => o.Projects.FindByName("Octopus", null, null)).Returns(project);
            octoRepo.Setup(o => o.Projects.FindByName("Gibberish", null, null)).Returns((ProjectResource)null);

            octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet);

            var process = new DeploymentProcessResource();

            process.Steps.Add(new DeploymentStepResource {
                Name = "Website", Id = "Step-1"
            });
            octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process);

            var envs = new List <EnvironmentResource>
            {
                new EnvironmentResource {
                    Id = "Environments-1", Name = "DEV"
                }
            };

            octoRepo.Setup(o => o.Environments.FindByNames(new[] { "DEV" }, null, null)).Returns(envs);
            var machines = new List <MachineResource>
            {
                new MachineResource {
                    Id = "Machines-1", Name = "web-01"
                }
            };

            octoRepo.Setup(o => o.Machines.FindByNames(new[] { "web-01" }, null, null)).Returns(machines);
        }
        public GetStepTests()
        {
            _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetStep));
            var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable);

            const string deploymentProcessId = "deploymentprocess-projects-1";

            // Create a project
            var projectResources = new List <ProjectResource>
            {
                new ProjectResource {
                    Name = "Octopus", DeploymentProcessId = deploymentProcessId, Id = "projects-1"
                }
            };

            octoRepo.Setup(o => o.Projects.FindByNames(new[] { "Octopus" }, null, null)).Returns(projectResources);
            octoRepo.Setup(o => o.Projects.FindByNames(new[] { "Gibberish" }, null, null)).Returns(new List <ProjectResource>());
            octoRepo.Setup(o => o.Projects.Get("projects-1")).Returns(projectResources[0]);
            octoRepo.Setup(o => o.Projects.Get("Gibberish")).Throws(new OctopusResourceNotFoundException("Not Found"));

            var process = new DeploymentProcessResource();

            //{
            //    Id = "deploymentprocess-projects-1"
            //};
            process.Steps.Add(new DeploymentStepResource {
                Name = "Test Step"
            });
            process.Steps.Add(new DeploymentStepResource {
                Name = "Test Step 2"
            });

            octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsIn(new[] { deploymentProcessId })))
            .Returns(process);

            octoRepo.Setup(o => o.DeploymentProcesses.Get(It.IsNotIn(new[] { deploymentProcessId })))
            .Throws(new OctopusResourceNotFoundException("Not Found"));
        }
Exemple #19
0
        /// <summary>
        /// ProcessRecord
        /// </summary>
        protected override void ProcessRecord()
        {
            _oldProject = _octopus.Projects.FindByName(Name);

            if (_oldProject == null)
            {
                throw new Exception(string.Format("Project '{0}' was not found.", Name));
            }

            var group = _octopus.ProjectGroups.FindByName(ProjectGroup);

            if (group == null)
            {
                throw new Exception(string.Format("Project Group '{0}' was not found.", ProjectGroup));
            }

            CreateNewProject(group.Id);

            _oldProcess = _octopus.DeploymentProcesses.Get(_oldProject.DeploymentProcessId);
            _newProcess = _octopus.DeploymentProcesses.Get(_newProject.DeploymentProcessId);

            CopyProcess();
            CopyVariables();
        }
        public UpdateLibraryVariableTests()
        {
            _ps = Utilities.CreatePowerShell(CmdletName, typeof(UpdateLibraryVariable));
            var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable);

            // Create some library variable sets
            _sets.Clear();
            _sets.Add(new LibraryVariableSetResource {
                Id = "LibraryVariableSets-1", Name = "ConnectionStrings", VariableSetId = "variables-1"
            });
            _sets.Add(new LibraryVariableSetResource {
                Id = "LibraryVariableSets-3", Name = "Service Endpoints", VariableSetId = "variables-3"
            });

            var variable = new VariableResource
            {
                Id          = "variables-1",
                Name        = "Test",
                Value       = "Test Value",
                IsSensitive = false
            };

            variable.Scope.Add(ScopeField.Action, "actions-1");
            variable.Scope.Add(ScopeField.Environment, "environments-1");
            variable.Scope.Add(ScopeField.Role, "DB");

            _variableSet.Variables.Add(variable);

            _sets[0].Links.Add("Variables", "variablesets-1");
            octoRepo.Setup(o => o.LibraryVariableSets.FindOne(It.IsAny <Func <LibraryVariableSetResource, bool> >(), It.IsAny <string>(), It.IsAny <object>()))
            .Returns(
                (Func <LibraryVariableSetResource, bool> f, string path, object pathParams) =>
                (from l in _sets where f(l) select l).FirstOrDefault());
            octoRepo.Setup(o => o.Projects.FindByName("Gibberish", null, null)).Returns((ProjectResource)null);

            octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet);

            var process = new DeploymentProcessResource();

            process.Steps.Add(new DeploymentStepResource {
                Name = "Website", Id = "Step-1"
            });
            octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process);

            var envs = new List <EnvironmentResource>
            {
                new EnvironmentResource {
                    Id = "environments-1", Name = "DEV"
                },
                new EnvironmentResource {
                    Id = "environments-2", Name = "TEST"
                }
            };

            octoRepo.Setup(o => o.Environments.FindByNames(It.IsAny <string[]>(), It.IsAny <string>(), It.IsAny <object>()))
            .Returns((string[] names, string path, object pathParams) => (from n in names
                                                                          from e in envs
                                                                          where e.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase)
                                                                          select e).ToList());

            var machines = new List <MachineResource>
            {
                new MachineResource {
                    Id = "machines-1", Name = "db-01"
                },
                new MachineResource {
                    Id = "machines-2", Name = "web-01"
                }
            };

            octoRepo.Setup(o => o.Machines.FindByNames(It.IsAny <string[]>(), It.IsAny <string>(), It.IsAny <object>())).Returns(
                (string[] names, string path, object pathParams) => (from n in names
                                                                     from m in machines
                                                                     where m.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase)
                                                                     select m).ToList());
        }
 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);
 }
Exemple #22
0
        public void Init()
        {
            _ps = Utilities.CreatePowerShell(CmdletName, typeof(UpdateVariable));
            var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable);

            var variable = new VariableResource
            {
                Id          = "variables-1",
                Name        = "Test",
                Value       = "Test Value",
                IsSensitive = false
            };

            variable.Scope.Add(ScopeField.Action, "actions-1");
            variable.Scope.Add(ScopeField.Environment, "environments-1");
            variable.Scope.Add(ScopeField.Role, "DB");

            _variableSet.Variables.Add(variable);

            var project = new ProjectResource {
                DeploymentProcessId = "deploymentprocesses-1"
            };

            project.Links.Add("Variables", "variablesets-1");
            octoRepo.Setup(o => o.Projects.FindByName("Octopus")).Returns(project);
            octoRepo.Setup(o => o.Projects.FindByName("Gibberish")).Returns((ProjectResource)null);

            octoRepo.Setup(o => o.VariableSets.Get("variablesets-1")).Returns(_variableSet);

            var process = new DeploymentProcessResource();

            process.Steps.Add(new DeploymentStepResource {
                Name = "Website", Id = "Step-1"
            });
            octoRepo.Setup(o => o.DeploymentProcesses.Get("deploymentprocesses-1")).Returns(process);

            var envs = new List <EnvironmentResource>
            {
                new EnvironmentResource {
                    Id = "environments-1", Name = "DEV"
                },
                new EnvironmentResource {
                    Id = "environments-2", Name = "TEST"
                }
            };

            octoRepo.Setup(o => o.Environments.FindByNames(It.IsAny <string[]>()))
            .Returns((string[] names) => (from n in names
                                          from e in envs
                                          where e.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase)
                                          select e).ToList());

            var machines = new List <MachineResource>
            {
                new MachineResource {
                    Id = "machines-1", Name = "db-01"
                },
                new MachineResource {
                    Id = "machines-2", Name = "web-01"
                }
            };

            octoRepo.Setup(o => o.Machines.FindByNames(It.IsAny <string[]>())).Returns(
                (string[] names) => (from n in names
                                     from m in machines
                                     where m.Name.Equals(n, StringComparison.InvariantCultureIgnoreCase)
                                     select m).ToList());
        }
 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)));
 }
Exemple #25
0
        public void Setup()
        {
            // setup data objects
            channelVersionRules = new List <ChannelVersionRuleResource>();
            projectResource     = new ProjectResource
            {
                DeploymentProcessId = TestHelpers.GetId("deploymentprocess"),
                Id = TestHelpers.GetId("project")
            };
            deploymentProcessResource = new DeploymentProcessResource
            {
                ProjectId = projectResource.Id,
                Id        = projectResource.DeploymentProcessId
            };

            releaseTemplateResource = new ReleaseTemplateResource
            {
                DeploymentProcessId = projectResource.DeploymentProcessId,
                Packages            = new List <ReleaseTemplatePackage>(),
                Id = TestHelpers.GetId("releaseTemplate")
            };
            channelResource = new ChannelResource
            {
                IsDefault = true,
                Id        = TestHelpers.GetId("channel"),
                ProjectId = projectResource.Id,
                Rules     = channelVersionRules,
                Name      = TestHelpers.GetId("channelname")
            };
            feedResource = new FeedResource
            {
                Links = new LinkCollection {
                    { "SearchTemplate", TestHelpers.GetId("searchUri") }
                }
            };

            // setup mocks
            logger            = Substitute.For <ILogger>();
            versionResolver   = Substitute.For <IPackageVersionResolver>();
            versionRuleTester = Substitute.For <IChannelVersionRuleTester>();

            deploymentProcessRepository = Substitute.For <IDeploymentProcessRepository>();
            deploymentProcessRepository.Get(projectResource.DeploymentProcessId)
            .Returns(Task.FromResult(deploymentProcessResource));
            deploymentProcessRepository
            .GetTemplate(Arg.Is <DeploymentProcessResource>(deploymentProcessResource),
                         Arg.Is <ChannelResource>(channelResource)).Returns(Task.FromResult(releaseTemplateResource));
            versionRuleTester
            .Test(Arg.Any <IOctopusAsyncRepository>(), Arg.Any <ChannelVersionRuleResource>(), Arg.Any <string>())
            .Returns(Task.FromResult(channelVersionRuleTestResult));

            releaseRepository = Substitute.For <IReleaseRepository>();
            feedRepository    = Substitute.For <IFeedRepository>();
            feedRepository.Get(Arg.Any <string>()).Returns(feedResource);

            repository = Substitute.For <IOctopusAsyncRepository>();
            repository.DeploymentProcesses.Returns(deploymentProcessRepository);
            repository.Releases.Returns(releaseRepository);
            repository.Feeds.Returns(feedRepository);
            repository.Client
            .Get <List <PackageResource> >(Arg.Any <string>(), Arg.Any <IDictionary <string, object> >()).Returns(packages);

            builder = new ReleasePlanBuilder(logger, versionResolver, versionRuleTester);
        }
 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))));
 }
 public static VariableResource UpdateWith(this VariableResource resource, Variable model, IOctopusRepository repository, DeploymentProcessResource deploymentProcess, ProjectResource project)
 {
     resource.Name        = model.Name;
     resource.IsEditable  = model.IsEditable;
     resource.IsSensitive = model.IsSensitive;
     resource.Value       = model.Value;
     resource.Prompt      = model.Prompt?.FromModel();
     resource.Scope.UpdateWith(model.Scope, repository, deploymentProcess, project);
     return(resource);
 }
Exemple #28
0
        /// <summary>
        /// Updates the passed Project's Deployment Process
        /// </summary>
        /// <param name="octRepository">The repository to call against.</param>
        /// <param name="project"></param>
        /// <param name="deploymentProcess"></param>
        public static void UpdateProjectDeploymentProcess(OctopusRepository octRepository, ProjectResource project, DeploymentProcessResource deploymentProcess)
        {
            var oldDeploymentProcess = GetDeploymentProcessFromProject(octRepository, project);

            UpdateDeploymentProcessFromDeploymentProcess(octRepository, deploymentProcess, oldDeploymentProcess);
        }
        static void Main(string[] args)
        {
            var apiKey              = "API-XXXXXXXXXXXXXXXXXXXXXXXXXX";
            var octopusURL          = "https://octopus.url";
            var projectName         = "testproject2";
            var releaseVersion      = "";
            var channelName         = "Default";
            var environmentName     = "Dev";
            var fixedPackageVersion = "";

            var endpoint   = new OctopusServerEndpoint(octopusURL, apiKey);
            var repository = new OctopusRepository(endpoint);

            var project     = repository.Projects.FindByName(projectName);
            var environment = repository.Environments.FindByName(environmentName);

            var template = new ReleaseTemplateResource();
            var process  = new DeploymentProcessResource();

            process = repository.DeploymentProcesses.Get(project.DeploymentProcessId);
            var channel = repository.Channels.FindByName(project, channelName);

            template = repository.DeploymentProcesses.GetTemplate(process, channel);

            //if you dont pass a value to newReleaseVersion, It'll calculate it using the version template of your project. Just like when you hit the "Create Release" button from the web portal
            if (string.IsNullOrEmpty(releaseVersion))
            {
                releaseVersion = template.NextVersionIncrement;
            }

            //Creating the release object
            var newrelease = new ReleaseResource
            {
                ProjectId = project.Id,
                Version   = releaseVersion
            };

            foreach (var package in template.Packages)
            {
                var selectedPackage = new SelectedPackage
                {
                    ActionName           = package.ActionName,
                    PackageReferenceName = package.PackageReferenceName
                };

                //If you don't pass a value to FixedPackageVersion, Octopus will look for the latest one in the feed.
                if (string.IsNullOrEmpty(fixedPackageVersion))
                {
                    //Gettin the latest version of the package available in the feed.
                    //This is probably the most complicated line. The expression can get tricky, as a step(action) might be a parent and have many children(more nested actions)
                    var packageStep =
                        process.Steps.FirstOrDefault(s => s.Actions.Any(a => a.Name == selectedPackage.ActionName))?
                        .Actions.FirstOrDefault(a => a.Name == selectedPackage.ActionName);

                    var packageId = packageStep.Properties["Octopus.Action.Package.PackageId"].Value;
                    var feedId    = packageStep.Properties["Octopus.Action.Package.FeedId"].Value;

                    var feed = repository.Feeds.Get(feedId);

                    var latestPackageVersion = repository.Feeds.GetVersions(feed, new[] { packageId }).FirstOrDefault();

                    selectedPackage.Version = latestPackageVersion.Version;
                }
                else
                {
                    selectedPackage.Version = fixedPackageVersion;
                }

                newrelease.SelectedPackages.Add(selectedPackage);
            }

            //Creating the release in Octopus
            var release = repository.Releases.Create(newrelease);

            //creating the deployment object
            var deployment = new DeploymentResource
            {
                ReleaseId     = release.Id,
                ProjectId     = project.Id,
                EnvironmentId = environment.Id
            };

            //Deploying the release in Octopus
            repository.Deployments.Create(deployment);
        }
Exemple #30
0
 public ChannelEditor AddCommonRuleForAllActions(string versionRange, string tagRegex, DeploymentProcessResource process)
 {
     Instance.AddCommonRuleForAllActions(versionRange, tagRegex, process);
     return(this);
 }