static void Main(string[] args)
        {
            var apiKey     = "API-XXXXXXXXXXXXXXXXXXXXXXXXXX";
            var octopusURL = "https://octopus.url";

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

            var actionTemplates = repository.ActionTemplates.GetAll();

            foreach (var actionTemplate in actionTemplates)
            {
                var usages         = client.Get <ActionTemplateUsageResource[]>(actionTemplate.Links["Usage"]);
                var usagesToUpdate = usages.Where(u => u.Version != actionTemplate.Version.ToString());

                if (!usagesToUpdate.Any())
                {
                    continue;
                }

                var actionsByProcessId   = usagesToUpdate.GroupBy(u => u.DeploymentProcessId);
                var actionIdsByProcessId = actionsByProcessId.ToDictionary(g => g.Key, g => g.Select(u => u.ActionId).ToArray());

                var actionUpdate = new ActionsUpdateResource();
                actionUpdate.Version = actionTemplate.Version;
                actionUpdate.ActionIdsByProcessId = actionIdsByProcessId;
                repository.ActionTemplates.UpdateActions(actionTemplate, actionUpdate);
            }
        }
Esempio n. 2
0
        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);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// ProcessRecord
        /// </summary>
        protected override void ProcessRecord()
        {
            var octopusServerEndpoint = new OctopusServerEndpoint(Server, ApiKey);
            var octopus = new OctopusRepository(octopusServerEndpoint);

            SessionState.PSVariable.Set("OctopusRepository", octopus);
        }
        public void Execute(string[] commandLineArguments)
        {
            var remainingArguments = optionGroups.Parse(commandLineArguments);

            if (remainingArguments.Count > 0)
            {
                throw new CommandException("Unrecognized command arguments: " + string.Join(", ", remainingArguments));
            }

            if (string.IsNullOrWhiteSpace(serverBaseUrl))
            {
                throw new CommandException("Please specify the Octopus Server URL using --server=http://your-server/");
            }

            if (string.IsNullOrWhiteSpace(apiKey) && (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)))
            {
                throw new CommandException("Please specify either your API key using --apiKey=ABCDEF123456789, or your Octopus credentials using --user=MyName --pass=Secret.");
            }

            var credentials = ParseCredentials(username, password);

            var endpoint = new OctopusServerEndpoint(serverBaseUrl, apiKey, credentials);

            repository = repositoryFactory.CreateRepository(endpoint);

            repository.Client.SendingOctopusRequest += request => log.Debug("{Method} {Uri}", request.Method, request.Uri);

            ConfigureServerCertificateValidation();

            InitializeConnection();

            Execute();
        }
Esempio n. 5
0
        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);
        }
Esempio n. 6
0
 public DeployPublisher(IDiscordBot bot, IOctopusClientFactory octopusClientFactory, OctopusServerEndpoint octopusServerEndpoint, ILogger <DeployPublisher> logger)
 {
     this._bot = bot ?? throw new ArgumentNullException(nameof(bot));
     this._octopusClientFactory  = octopusClientFactory ?? throw new ArgumentNullException(nameof(octopusClientFactory));
     this._octopusServerEndpoint = octopusServerEndpoint ?? throw new ArgumentNullException(nameof(octopusServerEndpoint));
     this._logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Esempio n. 7
0
        public string CreateProject()
        {
            var endpoint   = new OctopusServerEndpoint(_config.OctopusEndpointUrl, _config.ApiKey);
            var repository = new OctopusRepository(endpoint);

            repository.Projects.Create()
        }
Esempio n. 8
0
 static void Main(string[] args)
 {
     var server     = EnvironmentHelpers.GetServerUrl();
     var apiKey     = EnvironmentHelpers.GetApiKey();
     var endpoint   = new OctopusServerEndpoint(server, apiKey);
     var repository = new OctopusRepository(endpoint);
 }
Esempio n. 9
0
        private static void Run(int id, int interval)
        {
            new Thread(() =>
            {
                var instance = _instances[id];
                Console.WriteLine("Starting " + instance.Machine);
                var endpoint   = new OctopusServerEndpoint($"http://{instance.PublicIp}:81/");
                var repository = new OctopusRepository(endpoint);
                repository.Users.SignIn("Admin", "password");


                while (_running)
                {
                    try
                    {
                        Console.WriteLine(instance.Machine);
                        Run(repository, instance);
                        Thread.Sleep(TimeSpan.FromSeconds(interval));
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e.Message);
                    }
                }
            }).Start();
        }
Esempio n. 10
0
        public void Execute(string[] commandLineArguments)
        {
            var remainingArguments = optionGroups.Parse(commandLineArguments);

            if (remainingArguments.Count > 0)
            {
                throw new CommandException("Unrecognized command arguments: " + string.Join(", ", remainingArguments));
            }

            if (string.IsNullOrWhiteSpace(serverBaseUrl))
            {
                throw new CommandException("Please specify the Octopus Server URL using --server=http://your-server/");
            }

            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new CommandException("Please specify your API key using --apiKey=ABCDEF123456789. Learn more at: https://github.com/OctopusDeploy/Octopus-Tools");
            }

            var credentials = ParseCredentials(user, pass);

            var endpoint = new OctopusServerEndpoint(serverBaseUrl, apiKey, credentials);

            repository = repositoryFactory.CreateRepository(endpoint);

            if (enableDebugging)
            {
                repository.Client.SendingOctopusRequest += request => log.Debug(request.Method + " " + request.Uri);
            }

            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
            {
                if (errors == SslPolicyErrors.None)
                {
                    return(true);
                }

                var certificate2 = (X509Certificate2)certificate;
                var warning      = "The following certificate errors were encountered when establishing the HTTPS connection to the server: " + errors + Environment.NewLine +
                                   "Certificate subject name: " + certificate2.SubjectName.Name + Environment.NewLine +
                                   "Certificate thumbprint:   " + ((X509Certificate2)certificate).Thumbprint;

                if (ignoreSslErrors)
                {
                    log.Warn(warning);
                    log.Warn("Because --ignoreSslErrors was set, this will be ignored.");
                    return(true);
                }

                log.Error(warning);
                return(false);
            };

            log.Debug("Handshaking with Octopus server: " + serverBaseUrl);
            var root = repository.Client.RootDocument;

            log.Debug("Handshake successful. Octopus version: " + root.Version + "; API version: " + root.ApiVersion);

            Execute();
        }
Esempio n. 11
0
        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);
        }
        /// <summary>
        /// Executes the operation against the specified Octopus Deploy server.
        /// </summary>
        /// <param name="serverEndpoint">The Octopus Deploy server endpoint.</param>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        public void Execute(OctopusServerEndpoint serverEndpoint)
        {
            using (var client = clientFactory.CreateClient(serverEndpoint))
            {
                var repository = new OctopusRepository(client);

                Execute(repository);
            }
        }
        /// <summary>
        /// Executes the operation against the specified Octopus Deploy server.
        /// </summary>
        /// <param name="serverEndpoint">The Octopus Deploy server endpoint.</param>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        public async Task ExecuteAsync(OctopusServerEndpoint serverEndpoint)
        {
            using (var client = await clientFactory.CreateAsyncClient(serverEndpoint).ConfigureAwait(false))
            {
                var repository = new OctopusAsyncRepository(client);

                await ExecuteAsync(repository).ConfigureAwait(false);
            }
        }
Esempio n. 14
0
        private OctopusRepository GetOctopusRepository()
        {
            if (endpoint == null)
            {
                endpoint = new OctopusServerEndpoint(uri, apiKey);
            }

            return(new OctopusRepository(endpoint));
        }
Esempio n. 15
0
        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());
        }
Esempio n. 16
0
        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();
            }
        }
Esempio n. 17
0
        protected override void ProcessRecord()
        {
            var connection = new OctopusConnection();

            var endpoint = new OctopusServerEndpoint(_server, _apikey);

            connection.Repository = new OctopusRepository(endpoint);
            connection.Header.Add("X-Octopus-APIKey", _apikey);

            WriteObject(connection);
        }
Esempio n. 18
0
        public OctopusService(ICacheManager cacheManager)
        {
            ServerUrl = ConfigurationManager.AppSettings["OctopusServerUrl"];
            ApiKey    = ConfigurationManager.AppSettings["OctopusApiKey"];

            var endpoint = new OctopusServerEndpoint(ServerUrl, ApiKey);

            _repository = new OctopusRepository(endpoint);

            _cahManager = cacheManager;
        }
Esempio n. 19
0
        public OctopusProxy(IOptions <AppSettings> settings, IHttpContextAccessor httpContextAccessor)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var apiKey = httpContextAccessor.HttpContext.User.GetOctopusApiKey();

            _endpoint = new OctopusServerEndpoint(settings.Value.OctopusServerAddress, apiKey);
        }
Esempio n. 20
0
        private static void Main(string[] args)
        {
            try
            {
                var parametersDictionary = new Dictionary <ParameterEnum, string>();
                if (args.Length == 4)
                {
                    parametersDictionary.Add(ParameterEnum.ServerUrl, args[0].Trim());
                    parametersDictionary.Add(ParameterEnum.ApiKey, args[1].Trim());
                    parametersDictionary.Add(ParameterEnum.ProjectName, args[2].Trim());
                    parametersDictionary.Add(ParameterEnum.OutputPath, args[3].Trim());
                }
                else
                {
                    Console.WriteLine($"Required the parameter of ServerUrl, ApiKey and ProjectName");
                    Environment.Exit(1);
                }

                var endpoint   = new OctopusServerEndpoint(parametersDictionary[ParameterEnum.ServerUrl], parametersDictionary[ParameterEnum.ApiKey]);
                var repository = new OctopusRepository(endpoint);

                var project = repository.Projects.FindOne(p => p.Name == parametersDictionary[ParameterEnum.ProjectName]);

                var variablesList = new List <VariableViewModel>();

                //Dictionary to get Names from Ids
                var scopeNames = repository.Environments.FindAll().ToDictionary(x => x.Id, x => x.Name);
                repository.Machines.FindAll().ToList().ForEach(x => scopeNames[x.Id] = x.Name);
                repository.Projects.GetChannels(project).Items.ToList().ForEach(x => scopeNames[x.Id] = x.Name);

                var allEnvironments = repository.Environments.FindAll();

                var allRoles = repository.MachineRoles.GetAllRoleNames();

                var deploymentSteps = repository.DeploymentProcesses.Get(project.DeploymentProcessId).Steps.ToList();

                deploymentSteps.SelectMany(x => x.Actions).ToList().ForEach(x => scopeNames[x.Id] = x.Name);

                //Get All Library Set Variables
                var allVariables = repository.LibraryVariableSets.FindAll();

                ExportVariableSets(parametersDictionary, deploymentSteps, repository, project, variablesList, scopeNames, allVariables, allEnvironments);

                //var input = Console.ReadLine();
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Error {ex.Message}|{ex.StackTrace}");
                Environment.Exit(1);
                throw ex;
            }
        }
Esempio n. 21
0
        public async Task Execute(string[] commandLineArguments)
        {
            var remainingArguments = Options.Parse(commandLineArguments);

            if (remainingArguments.Count > 0)
            {
                throw new CommandException("Unrecognized command arguments: " + string.Join(", ", remainingArguments));
            }

            if (string.IsNullOrWhiteSpace(ServerBaseUrl))
            {
                throw new CommandException("Please specify the Octopus Server URL using --server=http://your-server/");
            }

            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new CommandException("Please specify your API key using --apiKey=ABCDEF123456789. Learn more at: https://github.com/OctopusDeploy/Octopus-Tools");
            }

            var credentials = ParseCredentials(username, password);

            var endpoint = new OctopusServerEndpoint(ServerBaseUrl, apiKey, credentials);

            client = await clientFactory.CreateAsyncClient(endpoint, new OctopusClientOptions()
            {
#if HTTP_CLIENT_SUPPORTS_SSL_OPTIONS
                IgnoreSslErrors = ignoreSslErrors
#endif
            }).ConfigureAwait(false);

            Repository = repositoryFactory.CreateRepository(client);
            RepositoryCommonQueries = new OctopusRepositoryCommonQueries(Repository, Log);

            if (enableDebugging)
            {
                Repository.Client.SendingOctopusRequest += request => Log.Debug("{Method:l} {Uri:l}", request.Method, request.Uri);
            }

            Log.Debug("Handshaking with Octopus server: {Url:l}", ServerBaseUrl);
            var root = Repository.Client.RootDocument;
            Log.Debug("Handshake successful. Octopus version: {Version:l}; API version: {ApiVersion:l}", root.Version, root.ApiVersion);

            var user = await Repository.Users.GetCurrent().ConfigureAwait(false);

            if (user != null)
            {
                Log.Debug("Authenticated as: {Name:l} <{EmailAddress:l}> {IsService:l}", user.DisplayName, user.EmailAddress, user.IsService ? "(a service account)" : "");
            }

            ValidateParameters();
            await Execute().ConfigureAwait(false);
        }
Esempio n. 22
0
        public void CreateClient()
        {
            if (_client != null)
            {
                return;
            }

            var endpoint = new OctopusServerEndpoint(_inputs.OctopusURL, _inputs.OctopusApiKey);
            var client   = new OctopusClient(endpoint);

            _client = client;
            return;
        }
Esempio n. 23
0
        public OctopusProxy(IOptions <AppSettings> settings, IHttpContextAccessor httpContextAccessor)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var apiKey = httpContextAccessor.HttpContext.User.GetOctopusApiKey();

            var endpoint = new OctopusServerEndpoint(settings.Value.OctopusServerAddress, apiKey);

            _octopusClient = Octopus.Client.OctopusAsyncClient.Create(endpoint, new OctopusClientOptions()).Result;
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            var server     = EnvironmentHelpers.GetServerUrl();
            var apiKey     = EnvironmentHelpers.GetApiKey();
            var endpoint   = new OctopusServerEndpoint(server, apiKey);
            var repository = new OctopusRepository(endpoint);

            var tenantResources = repository.Tenants.FindByName("Team 😄");

            ConsoleHelpers.Dump(tenantResources);

            Console.ReadKey();
        }
Esempio n. 25
0
        public async Task Execute(string[] commandLineArguments)
        {
            var remainingArguments = optionGroups.Parse(commandLineArguments);

            if (remainingArguments.Count > 0)
            {
                throw new CommandException("Unrecognized command arguments: " + string.Join(", ", remainingArguments));
            }

            if (string.IsNullOrWhiteSpace(serverBaseUrl))
            {
                serverBaseUrl = "http://localhost:8065";
                log.Information($"No Octopus Server URL was provided. Using default development value: {serverBaseUrl}");
            }

            if (string.IsNullOrWhiteSpace(apiKey) &&
                string.IsNullOrWhiteSpace(username) &&
                string.IsNullOrWhiteSpace(password))
            {
                username = "******";
                password = "******";
                log.Information("No credentials were provided. Using default development credentials.");
            }

            if (string.IsNullOrWhiteSpace(serverBaseUrl))
            {
                throw new CommandException("Please specify the Octopus Server URL using --server=http://your-server/");
            }

            if (string.IsNullOrWhiteSpace(apiKey) && (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)))
            {
                throw new CommandException("Please specify either your API key using --apiKey=ABCDEF123456789, or your Octopus credentials using --user=MyName --pass=Secret.");
            }

            var credentials = ParseCredentials(username, password);

            var endpoint = new OctopusServerEndpoint(serverBaseUrl, apiKey, credentials);

            using (var client = await octopusClientFactory.CreateAsyncClient(endpoint))
            {
                Repository = client.Repository;
                client.SendingOctopusRequest +=
                    request => log.Debug("{Method} {Uri}", request.Method, request.Uri);

                ConfigureServerCertificateValidation();

                await InitializeConnection();

                await Execute();
            }
        }
Esempio n. 26
0
 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");
         }
     });
 }
Esempio n. 27
0
        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);
            }
        }
Esempio n. 28
0
        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 void SetUp()
        {
            clientFactory = Substitute.For <IOctopusClientFactory>();
            client        = Substitute.For <IOctopusAsyncClient>();
            clientFactory.CreateAsyncClient(Arg.Any <OctopusServerEndpoint>()).Returns(client);
            operation      = new RegisterMachineOperation(clientFactory);
            serverEndpoint = new OctopusServerEndpoint("http://octopus", "ABC123");

            environments    = new ResourceCollection <EnvironmentResource>(new EnvironmentResource[0], LinkCollection.Self("/foo"));
            machines        = new ResourceCollection <MachineResource>(new MachineResource[0], LinkCollection.Self("/foo"));
            machinePolicies = new ResourceCollection <MachinePolicyResource>(new MachinePolicyResource[0], LinkCollection.Self("/foo"));
            var rootDocument = new RootResource
            {
                ApiVersion = "3.0.0",
                Version    = "2099.0.0",
                Links      = LinkCollection.Self("/api")
                             .Add("Environments", "/api/environments")
                             .Add("Machines", "/api/machines")
                             .Add("MachinePolicies", "/api/machinepolicies")
                             .Add("CurrentUser", "/api/users/me")
                             .Add("SpaceHome", "/api/spaces")
            };

            client.Get <RootResource>(Arg.Any <string>()).Returns(rootDocument);
            client.Repository.LoadRootDocument().Returns(rootDocument);
            client.Get <SpaceResource[]>(Arg.Any <string>())
            .Returns(new[] { new SpaceResource()
                             {
                                 Id = "Spaces-1", IsDefault = true
                             } });
            client.Get <UserResource>(Arg.Any <string>()).Returns(new UserResource()
            {
                Links =
                {
                    { "Spaces", "" }
                }
            });
            client.Repository.HasLink(Arg.Any <string>()).Returns(ci => rootDocument.HasLink(ci.Arg <string>()));
            client.Repository.Link(Arg.Any <string>()).Returns(ci => rootDocument.Link(ci.Arg <string>()));

            client.When(x => x.Paginate(Arg.Any <string>(), Arg.Any <object>(), Arg.Any <Func <ResourceCollection <EnvironmentResource>, bool> >()))
            .Do(ci => ci.Arg <Func <ResourceCollection <EnvironmentResource>, bool> >()(environments));
            client.When(x => x.Paginate(Arg.Any <string>(), Arg.Any <object>(), Arg.Any <Func <ResourceCollection <MachineResource>, bool> >()))
            .Do(ci => ci.Arg <Func <ResourceCollection <MachineResource>, bool> >()(machines));
            client.When(x => x.Paginate(Arg.Any <string>(), Arg.Any <object>(), Arg.Any <Func <ResourceCollection <MachinePolicyResource>, bool> >()))
            .Do(ci => ci.Arg <Func <ResourceCollection <MachinePolicyResource>, bool> >()(machinePolicies));

            client.List <MachineResource>(Arg.Any <string>(), Arg.Any <object>()).Returns(machines);
        }
Esempio n. 30
0
        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);
        }
    static void Main(string[] args)
    {
        var endpoint = new OctopusServerEndpoint("[URL]", "[APIKey]");
        var _repository = new OctopusRepository(endpoint);

        string projectName = "[ProjectName]";
        ProjectResource project = _repository.Projects.FindOne(p => p.Name == projectName);

        var variablesList = new List<VariableViewModel>();

        //Dictionary to get Names from Ids
        Dictionary<string,string> scopeNames = _repository.Environments.FindAll().ToDictionary(x => x.Id, x => x.Name);
        _repository.Machines.FindAll().ToList().ForEach(x => scopeNames[x.Id] = x.Name);
        _repository.Projects.GetChannels(project).Items.ToList().ForEach(x => scopeNames[x.Id] = x.Name);
        _repository.DeploymentProcesses.Get(project.DeploymentProcessId).Steps.SelectMany(x=>x.Actions).ToList().ForEach(x => scopeNames[x.Id] = x.Name);

        //Get All Library Set Variables
        List<LibraryVariableSetResource> librarySets = _repository.LibraryVariableSets.FindAll();

        foreach (var libraryVariableSetResource in librarySets)
        {

            var variables = _repository.VariableSets.Get(libraryVariableSetResource.VariableSetId);
            var variableSetName = libraryVariableSetResource.Name;
            foreach (var variable in variables.Variables)
            {
                variablesList.Add(new VariableViewModel(variable, variableSetName, scopeNames));
            }

        }

        //Get All Project Variables for the Project
        var projectSets = _repository.VariableSets.Get(project.VariableSetId);

        foreach (var variable in projectSets.Variables)
        {
            variablesList.Add(new VariableViewModel(variable, projectName, scopeNames));
        }

        foreach (var vm in variablesList)
        {
            Console.WriteLine($"VariableSet:{vm.VariableSetName} Name:{vm.Name} Value:{vm.Value} Scope: {vm.Scope}");
        }

        var input = Console.ReadLine();
    }
        public void SetUp()
        {
            clientFactory = Substitute.For<IOctopusClientFactory>();
            client = Substitute.For<IOctopusAsyncClient>();
            clientFactory.CreateAsyncClient(Arg.Any<OctopusServerEndpoint>()).Returns(client);
            operation = new RegisterMachineOperation(clientFactory);
            serverEndpoint = new OctopusServerEndpoint("http://octopus", "ABC123");

            environments = new ResourceCollection<EnvironmentResource>(new EnvironmentResource[0], LinkCollection.Self("/foo"));
            machines = new ResourceCollection<MachineResource>(new MachineResource[0], LinkCollection.Self("/foo"));
            client.RootDocument.Returns(new RootResource {Links = LinkCollection.Self("/api").Add("Environments", "/api/environments").Add("Machines", "/api/machines")});

            client.When(x => x.Paginate(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<Func<ResourceCollection<EnvironmentResource>, bool>>()))
                .Do(ci => ci.Arg<Func<ResourceCollection<EnvironmentResource>, bool>>()(environments));

            client.When(x => x.Paginate(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<Func<ResourceCollection<MachineResource>, bool>>()))
                .Do(ci => ci.Arg<Func<ResourceCollection<MachineResource>, bool>>()(machines));

            client.List<MachineResource>(Arg.Any<string>(), Arg.Any<object>()).Returns(machines);
        }
        /// <summary>
        /// Executes the operation against the specified Octopus Deploy server.
        /// </summary>
        /// <param name="serverEndpoint">The Octopus Deploy server endpoint.</param>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        public void Execute(OctopusServerEndpoint serverEndpoint)
        {
            using (var client = clientFactory.CreateClient(serverEndpoint))
            {
                var repository = new OctopusRepository(client);

                Execute(repository);
            }
        }
        /// <summary>
        /// Executes the operation against the specified Octopus Deploy server.
        /// </summary>
        /// <param name="serverEndpoint">The Octopus Deploy server endpoint.</param>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        public async Task ExecuteAsync(OctopusServerEndpoint serverEndpoint)
        {
            using (var client = await clientFactory.CreateAsyncClient(serverEndpoint).ConfigureAwait(false))
            {
                var repository = new OctopusAsyncRepository(client);

                await ExecuteAsync(repository).ConfigureAwait(false);
            }
        }