public async Task <int> Execute(object command) { try { var settings = new FileInfo(".cache/octopus.settingsfile"); if (!settings.Exists) { Console.WriteLine("Please use the login command first to authenticate."); return(-1); } var login = JsonConvert.DeserializeObject <LoginSettings>(File.ReadAllText(settings.FullName)); using (var client = await OctopusAsyncClient.Create(new OctopusServerEndpoint(login.OctopusUri, login.ApiKey))) { var all = await client.Repository.LibraryVariableSets.FindAll(); foreach (var resource in all) { var variables = (await client.Repository.VariableSets.Get(resource.VariableSetId)).Variables; await _repository.Save(new CachedVariables { Variables = variables, Resource = resource }); Console.WriteLine($"Saved {resource.Name}."); } } return(0); } catch (Exception e) { Console.WriteLine(e.Message); return(-1); } }
public async Task <Dictionary <string, string> > GetArtifacts(string environmentName, string projectName, params string[] artifactNames) { var endpoint = new OctopusServerEndpoint(octopusEndpoint, octopusApiKey); var client = await OctopusAsyncClient.Create(endpoint); OctopusAsyncRepository repository = new OctopusAsyncRepository(client); var artifacts = await GetArtifactsList(repository, environmentName, projectName); var artifactsByName = new Dictionary <string, string>(); foreach (var artifactName in artifactNames) { var matchingArtifact = artifacts.Items.SingleOrDefault(a => a.Filename == artifactName); if (matchingArtifact == null) { throw new ArtifactsProviderException( $"У деплоя проекта {projectName} на среду {environmentName} отсутствует артефакт {artifactName}. " + "Проверьте свежесть и полноту деплоя."); } using (var stream = await repository.Artifacts.GetContent(matchingArtifact)) using (var streamReader = new StreamReader(stream)) { artifactsByName[artifactName] = await streamReader.ReadToEndAsync(); } } return(artifactsByName); }
public async Task InvalidSslCertificateIsRejected() { OctopusAsyncRepository.SecondsToWaitForServerToStart = 2; try { await OctopusAsyncClient.Create(new OctopusServerEndpoint(HostBaseSslUri + TestRootPath)).ConfigureAwait(false); Assert.Fail("Exception expected"); } catch (Exception ex) { var e = ex.InnerException?.InnerException; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { e.GetType().Name.Should().BeOneOf("WinHttpException", "AuthenticationException"); e.Message.Should().BeOneOf("A security error occurred", "The remote certificate is invalid according to the validation procedure."); } else { e.GetType().Name.Should().Be("CurlException"); e.Message.Should().Be("Peer certificate cannot be authenticated with given CA certificates"); } } OctopusAsyncRepository.SecondsToWaitForServerToStart = 60; }
private async Task InitializeClient() { if (_octopusClient == null) { _octopusClient = await OctopusAsyncClient.Create(_endpoint, new OctopusClientOptions()); } }
public async Task InvalidSslCertificateIsIgnoredWhenTheOptionIsOn() { try { var client = await OctopusAsyncClient.Create( new OctopusServerEndpoint(HostBaseSslUri + TestRootPath), new OctopusClientOptions() { IgnoreSslErrors = true } ); var result = await client.Get <string>("~/"); result.Should().Be("Data"); } catch (Exception ex) when(ex.Message == "This platform does not support ignoring SSL certificate errors") { var os = RuntimeInformation.OSDescription; if ( os.StartsWith("Darwin") || // Mac os.Contains(".el7") || // Cent OS os.Contains("fc23") // Fedora 23 ) { return; } throw; } }
private static async Task <int> PromoteRelease(string server, string apiKey, string environmentName, string projectName, string semVer) { Console.WriteLine($"Promoting Octopus Deploy Release for project: {projectName} {semVer} to environment: {environmentName}"); try { var octoEndpoint = new OctopusServerEndpoint(server, apiKey); using (var client = await OctopusAsyncClient.Create(octoEndpoint).ConfigureAwait(false)) { var octoRepository = client.Repository; var octoEnv = (await octoRepository.Environments.GetAll().ConfigureAwait(false)).First(x => x.Name.Equals(environmentName)); var octoProject = await octoRepository.Projects.FindOne(projectResource => projectResource.Name.Equals(projectName)).ConfigureAwait(false); var octoRelease = await octoRepository.Releases.FindOne(releaseResource => releaseResource.Version.Equals(semVer) && releaseResource.ProjectId.Equals(octoProject.Id)).ConfigureAwait(false); var octoDeploymentResource = new DeploymentResource { ReleaseId = octoRelease.Id, ProjectId = octoRelease.ProjectId, EnvironmentId = octoEnv.Id }; await octoRepository.Deployments.Create(octoDeploymentResource).ConfigureAwait(false); } return(0); } catch (Exception ex) { Console.WriteLine($"Octopus Deploy Promote Release failed with message:{Environment.NewLine}{ex.Message}{Environment.NewLine}{ex.StackTrace}"); return(1); } }
/// <summary> /// Returns a list of variables for an Octopus project, sorted by variable name /// </summary> /// <param name="projectName">The name of the Octopus project</param> public async Task <IEnumerable <VariableModel> > GetProjectVariables(string projectName) { using (var client = await OctopusAsyncClient.Create(_octopusServerEndpoint)) { var repository = client.CreateRepository(); var project = await GetProjectResource(projectName, repository); var variableSetResource = await repository.VariableSets.Get(project.VariableSetId); var variables = variableSetResource.Variables.Select(x => { if (x.IsSensitive) { return(new VariableModel { Name = x.Name, Value = "[SECRET]" }); } return(new VariableModel { Name = x.Name, Value = x.Value }); }) .ToList(); return(variables.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase)); } }
/// <summary> /// Gets all variables in a Library Variable Set which apply to an environment. This includes unscoped variables (which apply to all environments). /// </summary> /// <param name="libraryName">The name of the Library Variable Set</param> /// <param name="environment">The environment (scope) name (e.g. "Prod")</param> public async Task <IEnumerable <VariableModel> > GetLibraryVariablesForEnvironment(string libraryName, string environment) { using (var client = await OctopusAsyncClient.Create(_octopusServerEndpoint)) { var repository = client.CreateRepository(); var libraryVariableSetResource = await GetOctopusLibrarySet(libraryName, repository); var environmentResource = await GetEnvironmentResource(environment, repository); var variablesSetResource = await repository.VariableSets.Get(libraryVariableSetResource.VariableSetId); var variables = variablesSetResource.Variables .Where(x => x.Scope.IsNullOrEmpty() || (x.Scope.ContainsKey(ScopeField.Environment) && x.Scope[ScopeField.Environment].Contains(environmentResource.Id))) .Select(x => { if (x.IsSensitive) { return(new VariableModel { Name = x.Name, Value = "[SECRET]" }); } return(new VariableModel { Name = x.Name, Value = x.Value }); }); return(variables.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase)); } }
private static IOctopusAsyncClient InitClient(string url, string apikey) { var endpoint = new OctopusServerEndpoint(url, apikey); IOctopusAsyncClient client = null; Task.Run(async() => { client = await OctopusAsyncClient.Create(endpoint); }).Wait(); return(client); }
public async Task <ProjectResource> CreateProjectAsync(ProjectResource project) { using (var client = await OctopusAsyncClient.Create(_endpoint)) { var repo = client.CreateRepository(); return(await repo.Projects.Create(project)); } }
public async Task <ProjectGroupResource> CreateGroupAsync(ProjectGroupResource group) { using (var client = await OctopusAsyncClient.Create(_endpoint)) { var repo = client.CreateRepository(); return(await repo.ProjectGroups.Create(group)); } }
public async Task <string[]> GetEnvironments() { var endpoint = new OctopusServerEndpoint(octopusEndpoint, octopusApiKey); var client = await OctopusAsyncClient.Create(endpoint); OctopusAsyncRepository repository = new OctopusAsyncRepository(client); var environments = await repository.Environments.FindAll(); return(environments.Select(x => x.Name).ToArray()); }
public override void Run(DotNetCoreContext context) { var serverUrl = context.GetProperty <string>("octopusServerUrl"); var apiKey = context.GetProperty <string>("octopusApiKey"); var ep = new OctopusServerEndpoint(serverUrl, apiKey); using (var client = OctopusAsyncClient.Create(ep).GetAwaiter().GetResult()) { var repo = client.CreateRepository(); } }
public async System.Threading.Tasks.Task <List <LibraryVariableSetResource> > GetProjectVariablesAsync(string projectname, string environment) { using (var client = await OctopusAsyncClient.Create(octoClientSingle.Endpoint)) { var projectsTask = client.Repository.Projects.FindByName("Platform-MP-Quotes"); var project = projectsTask.Result; var variablesetTask = client.Repository.VariableSets.Get(project.VariableSetId); var variableSet = variablesetTask.Result; } return(new List <LibraryVariableSetResource>()); }
public OctopusAuthenticationProxy(IOptions <AppSettings> settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var octopusServerAddress = settings.Value.OctopusServerAddress; _repository = OctopusAsyncClient.Create(new OctopusServerEndpoint(octopusServerAddress), new OctopusClientOptions()).Result.Repository; }
/// <summary> /// Returns a list of all Environments, sorted by name /// </summary> public async Task <IEnumerable <string> > GetAllEnvironments() { using (var client = await OctopusAsyncClient.Create(_octopusServerEndpoint)) { var repository = client.CreateRepository(); var environmentResources = await repository.Environments.GetAll(); var environments = environmentResources.Select(x => x.Name).ToList(); environments.Sort(StringComparer.OrdinalIgnoreCase); return(environments); } }
/// <summary> /// Returns a list of all Octopus project names, sorted by project name /// </summary> public async Task <IEnumerable <string> > GetAllProjects() { using (var client = await OctopusAsyncClient.Create(_octopusServerEndpoint)) { var repository = client.CreateRepository(); var allProjects = await repository.Projects.GetAll(); var projectNames = allProjects.Select(x => x.Name) .ToList(); projectNames.Sort(StringComparer.OrdinalIgnoreCase); return(projectNames); } }
public List <ProjectResource> GetProjects() { var server = "https://gurdip-sira.octopus.app/"; var apiKey = "API-FVRZ6YTGFVWV5YJHMJL9A58BKXK"; // Get this from your 'profile' page in the Octopus web portal var endpoint = new OctopusServerEndpoint(server, apiKey); using (var client = OctopusAsyncClient.Create(endpoint)) { var repository = new OctopusRepository(endpoint); List <ProjectResource> prs = repository.Projects.GetAll(); return(prs); } }
public DashboardActor() { Receive <BaseApiMessage>(async msg => { var endpoint = new OctopusServerEndpoint(msg.Url, msg.ApiKey); using (var client = await OctopusAsyncClient.Create(endpoint)) { Stopwatch sw = Stopwatch.StartNew(); var dashboard = await client.Repository.Dashboards.GetDashboard(); sw.Stop(); Console.WriteLine($"Dashboard with {dashboard.Items.Count} items, {dashboard.Projects.Count} projects, received in {sw.ElapsedMilliseconds} ms"); } }); }
private static async Task <ProjectResource> GetProjectResource(BaseApiMessage msg) { ProjectResource project; var endpoint = new OctopusServerEndpoint(msg.Url, msg.ApiKey); using (var client = await OctopusAsyncClient.Create(endpoint)) { var projects = await client.Repository.Projects.GetAll(); project = projects.OrderBy(x => Guid.NewGuid()).First(); } return(project); }
public async Task <int> Run(IReadOnlyCollection <string> files, IReadOnlyCollection <string> variables) { var globalConfig = await GetGlobalConfig(); var currentDirectory = FileSystem.GetCurrentDirectory(); var endpoint = new OctopusServerEndpoint(globalConfig.Server, globalConfig.ApiKey); using (var client = await OctopusAsyncClient.Create(endpoint)) { await RecursivelySubstitute(files, client, currentDirectory, Static.GetSessionVariables(variables), globalConfig); } DebugLine(() => "Done"); return(0); }
public DeploymentProcessActor() { Receive <CreateDeploymentProcess>(async msg => { var endpoint = new OctopusServerEndpoint(msg.Url, msg.ApiKey); using (var client = await OctopusAsyncClient.Create(endpoint)) { DeploymentProcessEditor editor = new DeploymentProcessEditor(client.Repository.DeploymentProcesses); await editor.Load(msg.DeploymentProcessId); var addOrUpdateScriptAction = editor.AddOrUpdateStep("Script").AddOrUpdateScriptAction("Script", ScriptAction.InlineScript(ScriptSyntax.PowerShell, "Write-Host \"hello\""), ScriptTarget.Server); await editor.Save(); Console.WriteLine($"Created process for {msg.ProjectId}"); } }); }
public static async Task Run(int id) { var correlatedLog = Log.ForContext("CorrelationId", Guid.NewGuid()) .ForContext("Id", id); try { var sw = Stopwatch.StartNew(); var sw2 = Stopwatch.StartNew(); var endpoint = new OctopusServerEndpoint("http://54.79.14.25/" + id.ToString("000")); var client = await OctopusAsyncClient.Create(endpoint); var repository = client.Repository; await repository.Users.SignIn("Admin", "ThePassword"); LogOperation(correlatedLog, sw2, "Signin"); var dashboard = await repository.Dashboards.GetDashboard(); var latestRelease = dashboard.Items.OrderByDescending(d => d.StartTime).First(); LogOperation(correlatedLog, sw2, "Dashboard"); var summary = await repository.Environments.Summary(); LogOperation(correlatedLog, sw2, "Summary"); var project = await repository.Projects.Get(latestRelease.ProjectId); LogOperation(correlatedLog, sw2, "Project"); var task = await repository.Tasks.Get(latestRelease.TaskId); LogOperation(correlatedLog, sw2, "Task"); var logs = await repository.Tasks.GetDetails(task); LogOperation(correlatedLog, sw2, "TaskDetails"); correlatedLog.Information("Ran user script against {id} in {ms}", id, sw.ElapsedMilliseconds); } catch (Exception e) { correlatedLog.Warning(e, "Exception running user script"); } }
private static async Task <int> CreateRelease(string server, string apiKey, string projectName, string semVer, string releaseNotes) { Console.WriteLine($"Creating Octopus Deploy Release for project: {projectName} {semVer}"); try { var octoEndpoint = new OctopusServerEndpoint(server, apiKey); using (var client = await OctopusAsyncClient.Create(octoEndpoint).ConfigureAwait(false)) { var octoRepository = client.Repository; var octoProject = await octoRepository.Projects.FindOne(projectResource => projectResource.Name.Equals(projectName)).ConfigureAwait(false); var octoProcess = await octoRepository.DeploymentProcesses.Get(octoProject.DeploymentProcessId).ConfigureAwait(false); var octoChannel = await octoRepository.Client.Get <ChannelResource>($"/api/projects/{octoProject.Id}/channels").ConfigureAwait(false); var octoTemplate = await octoRepository.DeploymentProcesses.GetTemplate(octoProcess, octoChannel).ConfigureAwait(false); var octoReleaseResource = new ReleaseResource { Version = semVer, ProjectId = octoProject.Id, ReleaseNotes = releaseNotes }; foreach (var package in octoTemplate.Packages) { var selectedPackage = new SelectedPackage { ActionName = package.ActionName, Version = semVer }; octoReleaseResource.SelectedPackages.Add(selectedPackage); } await octoRepository.Releases.Create(octoReleaseResource).ConfigureAwait(false); } return(0); } catch (Exception ex) { Console.WriteLine($"Octopus Deploy Create Release failed with message:{Environment.NewLine}{ex.Message}{Environment.NewLine}{ex.StackTrace}"); return(1); } }
public async Task InvalidSslCertificateIsRejected() { OctopusAsyncRepository.SecondsToWaitForServerToStart = 2; try { await OctopusAsyncClient.Create(new OctopusServerEndpoint(HostBaseSslUri + TestRootPath)).ConfigureAwait(false); Assert.Fail("Exception expected"); } catch (Exception ex) { var e = ex.InnerException?.InnerException; e.GetType().Name.Should().Be("AuthenticationException"); e.Message.Should().Be("The remote certificate is invalid according to the validation procedure."); } OctopusAsyncRepository.SecondsToWaitForServerToStart = 60; }
public async Task <string> ValidateApiKey(string apiKey) { UserResource user; try { using (var client = await OctopusAsyncClient.Create(new OctopusServerEndpoint(_octopusServerAddress, apiKey))) { user = await client.Repository.Users.GetCurrent(); } } catch (OctopusSecurityException) { return(null); } return(user.Username); }
public async Task InvalidSslCertificateIsIgnoredWhenTheOptionIsOn() { try { var client = await OctopusAsyncClient.Create( new OctopusServerEndpoint(HostBaseSslUri + TestRootPath), new OctopusClientOptions() { IgnoreSslErrors = true } ).ConfigureAwait(false); var result = await client.Get <string>("~/").ConfigureAwait(false); result.Should().Be("Data"); } catch (Exception ex) when(ex.Message == "This platform does not support ignoring SSL certificate errors") { Console.WriteLine($"This test is running on '{RuntimeInformation.OSDescription}'"); if (File.Exists("/etc/os-release")) { var file = File.ReadAllText("/etc/os-release"); if (file.Contains("openSUSE Leap 15.1")) { Assert.Inconclusive($"This test is known not to work on platform 'openSuse Leap 15.1'"); } } var os = RuntimeInformation.OSDescription; if ( os.StartsWith("Darwin") || // Mac os.Contains(".el7") || // Cent OS os.Contains("fc23") // Fedora 23 ) { Assert.Inconclusive($"This test is known not to work on platform '{RuntimeInformation.OSDescription}'"); } throw; } }
private async Task UploadToOctopus(HttpClient httpClient, JArray assets) { Log.Information("Uploading assets to Octopus"); using (var octoClient = await OctopusAsyncClient.Create(octopusServerEndpoint)) { foreach (var assetToken in assets) { var assetName = (string)assetToken["name"]; var assetUrl = (string)assetToken["browser_download_url"]; using (var response = await httpClient.GetAsync(assetUrl)) { using (var content = response.Content) { Log.Information("Uploading asset {@asset} to octopus", new { name = assetName }); await octoClient.Repository.BuiltInPackageRepository.PushPackage(assetName, await content.ReadAsStreamAsync(), false); } } } } }
public ProjectCreatorActor() { Receive <CreateNewProject>(async msg => { var endpoint = new OctopusServerEndpoint(msg.Url, msg.ApiKey); using (var client = await OctopusAsyncClient.Create(endpoint)) { var projectGroup = await client.Repository.ProjectGroups.FindByName(msg.ProjectGroup); var project = await client.Repository.Projects.Create(new ProjectResource { ProjectGroupId = projectGroup.Id, Name = $"{msg.Name}{Guid.NewGuid()}", LifecycleId = "Lifecycles-1" }); msg.DeploymentProcessActor.Tell(new CreateDeploymentProcess(project.Id, project.DeploymentProcessId, msg.Url, msg.ApiKey)); Console.WriteLine($"New project created {project.Name}"); } }); }
/// <summary> /// Returns the repository class the tests will use to connect to Octopus /// </summary> /// <returns>Task<IOctopusAsyncRepository></returns> public static async Task <IOctopusAsyncRepository> GetRepository() { var config = new ConfigurationBuilder() .AddJsonFile("appConfig.json") .Build(); //getting data to connect to Octopus from appConfig.json var username = config["OctopusAdmin"]; var password = config["OctopusPassword"]; var octopuswebListenPort = config["OctopuswebListenPort"]; var serverUrl = "http://localhost:" + octopuswebListenPort; var client = await OctopusAsyncClient.Create(new OctopusServerEndpoint(serverUrl)); await client.Repository.Users.SignIn(new LoginCommand { Username = username, Password = password }); return(client.Repository); }