public VariableViewModel(VariableResource variable, string variableSetName, Dictionary<String, String> scopeNames)
    {
        Name = variable.Name;
        Value = variable.Value;
        VariableSetName = variableSetName;

        var nonLookupRoles =
            variable.Scope.Where(s => s.Key != ScopeField.Environment & s.Key != ScopeField.Machine & s.Key != ScopeField.Channel & s.Key != ScopeField.Action)
                .ToDictionary(dict => dict.Key, dict => dict.Value);

        foreach (var scope in nonLookupRoles)
        {
            if (string.IsNullOrEmpty(Scope))
                Scope = String.Join(",", scope.Value, Scope);
        }

        var lookupRoles =
            variable.Scope.Where(s => s.Key == ScopeField.Environment || s.Key == ScopeField.Machine || s.Key == ScopeField.Channel || s.Key == ScopeField.Action)
                .ToDictionary(dict => dict.Key, dict => dict.Value);

        foreach (var role in lookupRoles)
        {
            foreach (var scope in role.Value)
            {
                Scope = String.Join(",", scopeNames[scope], Scope);
            }
        }
    }
示例#2
0
        public void TestFetchResponse()
        {
            var twilioRestClient = Substitute.For <ITwilioRestClient>();

            twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            twilioRestClient.Request(Arg.Any <Request>())
            .Returns(new Response(
                         System.Net.HttpStatusCode.OK,
                         "{\"sid\": \"ZV00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"environment_sid\": \"ZE00000000000000000000000000000000\",\"key\": \"test-key\",\"value\": \"test-value\",\"date_created\": \"2018-11-10T20:00:00Z\",\"date_updated\": \"2018-11-10T20:00:00Z\",\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables/ZV00000000000000000000000000000000\"}"
                         ));

            var response = VariableResource.Fetch("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);

            Assert.NotNull(response);
        }
示例#3
0
        public void TestReadEmptyResponse()
        {
            var twilioRestClient = Substitute.For <ITwilioRestClient>();

            twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            twilioRestClient.Request(Arg.Any <Request>())
            .Returns(new Response(
                         System.Net.HttpStatusCode.OK,
                         "{\"variables\": [],\"meta\": {\"first_page_url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables?PageSize=50&Page=0\",\"key\": \"variables\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables?PageSize=50&Page=0\"}}"
                         ));

            var response = VariableResource.Read("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);

            Assert.NotNull(response);
        }
        public void TestFetchRequest()
        {
            var twilioRestClient = Substitute.For <ITwilioRestClient>();
            var request          = new Request(
                HttpMethod.Get,
                Twilio.Rest.Domain.Serverless,
                "/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Variables/ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                ""
                );

            twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));

            try
            {
                VariableResource.Fetch("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
                Assert.Fail("Expected TwilioException to be thrown for 500");
            }
            catch (ApiException) {}
            twilioRestClient.Received().Request(request);
        }
        /// <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);
        }
示例#6
0
        private List <VariableResource> CreateVariablesForVariableSet(VariableScopeValues variableSetScopeValues, int numberOfVariables)
        {
            return(Enumerable.Range(0, numberOfVariables).Select(i =>
            {
                var variable = new VariableResource()
                {
                    Name = $"{GenerateSomeVariableName()}",
                    IsEditable = true
                };

                bool shouldPrompt = _shouldPrompt.Get();
                if (shouldPrompt)
                {
                    variable.Prompt = new VariablePromptOptions()
                    {
                        Description = GenerateSomeVariableDescription(),
                        Label = GenerateSomeVariableName(),
                        Required = _required.Get()
                    };
                }

                variable.Scope = CreateScopeSpecification(variableSetScopeValues, shouldPrompt);

                // TODO: Add certificates
                // For new, only string and password types are supported
                bool isString = _isStringVariable.Get();
                if (isString)
                {
                    variable.Type = VariableType.String;
                    variable.Value = shouldPrompt ? string.Empty : GenerateSomeVariableValue();
                }
                else
                {
                    variable.Type = VariableType.Sensitive;
                    variable.Value = shouldPrompt ? string.Empty : GenerateSomeVariableValue();
                }

                return variable;
            }).ToList());
        }
        public void TestCreateRequest()
        {
            var twilioRestClient = Substitute.For <ITwilioRestClient>();
            var request          = new Request(
                HttpMethod.Post,
                Twilio.Rest.Domain.Serverless,
                "/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Environments/ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Variables",
                ""
                );

            request.AddPostParam("Key", Serialize("key"));
            request.AddPostParam("Value", Serialize("value"));
            twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));

            try
            {
                VariableResource.Create("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "key", "value", client: twilioRestClient);
                Assert.Fail("Expected TwilioException to be thrown for 500");
            }
            catch (ApiException) {}
            twilioRestClient.Received().Request(request);
        }
        private void ProcessByParts()
        {
            var variable = new VariableResource {
                Name = Name, Value = Value, IsSensitive = Sensitive
            };

            if (Environments != null)
            {
                AddEnvironments(variable);
            }

            if (Machines != null)
            {
                AddMachines(variable);
            }

            if (Roles != null && Roles.Length > 0)
            {
                variable.Scope.Add(ScopeField.Role, new ScopeValue(Roles));
            }

            _variableSet.Variables.Add(variable);
        }
        /// <summary>
        /// Gonna go out for a pack of smokes.
        /// </summary>
        /// <param name="octRepository">Ill be</param>
        /// <param name="variable">back</param>
        /// <param name="library">soon</param>
        public VariableInfoResource(OctopusRepository octRepository, VariableResource variable, LibraryVariableSetResource library)
        {
            Variable           = variable;
            LibraryVariableSet = library;
            LibrarySetName     = library.Name;
            VariableSetId      = library.VariableSetId;
            LibrarySetId       = library.Id;
            OctopusRepo        = octRepository;

            Id                  = variable.Id;
            Name                = variable.Name;
            Sensative           = variable.IsSensitive;
            Value               = variable.Value;
            DeploymentTimeValue = variable.Value;

            if (variable.Scope.Count > 0)
            {
                if (variable.Scope.ContainsKey(ScopeField.Environment))
                {
                    foreach (var environment in variable.Scope[ScopeField.Environment])
                    {
                        EnvironmentScope.Add(EnvironmentHelper.GetEnvironmentById(OctopusRepo, environment));
                    }
                }
                if (variable.Scope.ContainsKey(ScopeField.Role))
                {
                    RoleScope = variable.Scope[ScopeField.Role].ToList();
                }
                if (variable.Scope.ContainsKey(ScopeField.Machine))
                {
                    foreach (var machine in variable.Scope[ScopeField.Machine])
                    {
                        MachineScope.Add(MachineHelper.GetMachineById(OctopusRepo, machine));
                    }
                }
            }
        }
示例#10
0
        public void CopyVariables(IList <VariableResource> source, CopyScopeValue copyAction = null)
        {
            foreach (var variable in source)
            {
                if (variable.IsSensitive)
                {
                    const string warning =
                        "Variable '{0}' was sensitive. Sensitive flag has been removed and the value has been set to an empty string.";
                    _writeWarning(string.Format(warning, variable.Name));
                }

                var newVariable = new VariableResource
                {
                    Name        = variable.Name,
                    IsEditable  = variable.IsEditable,
                    IsSensitive = false,
                    Prompt      = variable.Prompt,
                    Value       = variable.IsSensitive ? "" : variable.Value,
                    Scope       = CreateScope(variable.Scope, copyAction)
                };

                _variableSet.Add(newVariable);
            }
        }
示例#11
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 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 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);
        }
        /// <summary>
        /// Removes a Variable to a Project's VariableSet.
        /// </summary>
        /// <param name="octRepository">The repository to call against.</param>
        /// <param name="project">Project to remove from.</param>
        /// <param name="variable"></param>
        public static void RemoveVariableFromProjectVariableSet(OctopusRepository octRepository, ProjectResource project, VariableResource variable)
        {
            var currentProjectVariables = GetVariableSetFromProject(octRepository, project);
            var variableToRemove        = currentProjectVariables.Variables.Where(x => x.Id == variable.Id).FirstOrDefault();

            currentProjectVariables.Variables.Remove(variableToRemove);
            octRepository.VariableSets.Modify(currentProjectVariables);
        }
        /// <summary>
        /// Adds a Variable to a Project's VariableSet.
        /// </summary>
        /// <param name="octRepository">The repository to call against.</param>
        /// <param name="project">Project to add to.</param>
        /// <param name="variable"></param>
        public static void AddVariableToProjectVariableSet(OctopusRepository octRepository, ProjectResource project, VariableResource variable)
        {
            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;
            var currentProjectVariables = GetVariableSetFromProject(octRepository, project);

            currentProjectVariables.Variables.Add(variableResource);
            octRepository.VariableSets.Modify(currentProjectVariables);
        }
示例#16
0
        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);
            }
        }