/// <summary>
 /// One of these fields must be present for a k8s step
 /// </summary>
 public bool IsEnabled(ScriptSyntax syntax)
 {
     return((!string.IsNullOrEmpty(variables.Get(SpecialVariables.ClusterUrl, "")) ||
             !string.IsNullOrEmpty(variables.Get(SpecialVariables.AksClusterName, "")) ||
             !string.IsNullOrEmpty(variables.Get(SpecialVariables.EksClusterName, ""))) &&
            syntax == ScriptSyntaxHelper.GetPreferredScriptSyntaxForEnvironment());
 }
        public void Install(RunningDeployment deployment)
        {
            ScriptSyntax syntax   = ScriptSyntaxHelper.GetPreferredScriptSyntaxForEnvironment();
            var          cmd      = BuildHelmCommand(deployment, syntax);
            var          fileName = SyntaxSpecificFileName(deployment, syntax);


            using (new TemporaryFile(fileName))
            {
                fileSystem.OverwriteFile(fileName, cmd);
                var result = scriptEngine.Execute(new Script(fileName), deployment.Variables, commandLineRunner);
                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format(
                                                   "Helm Upgrade returned non-zero exit code: {0}. Deployment terminated.", result.ExitCode));
                }

                if (result.HasErrors &&
                    deployment.Variables.GetFlag(Deployment.SpecialVariables.Action.FailScriptOnErrorOutput, false))
                {
                    throw new CommandException(
                              $"Helm Upgrade returned zero exit code but had error output. Deployment terminated.");
                }
            }
        }
Exemplo n.º 3
0
        public CommandResult ExecuteScript(Script script, ScriptSyntax scriptSyntax, ICommandLineRunner commandLineRunner, Dictionary <string, string>?environmentVars)
        {
            if (NextWrapper == null)
            {
                throw new InvalidOperationException("NextWrapper has not been set.");
            }

            var workingDirectory = Path.GetDirectoryName(script.File);

            if (workingDirectory == null)
            {
                throw new InvalidOperationException("Working directory has not been set correctly.");
            }

            variables.Set("OctopusFunctionAppenderTargetScript", $"{script.File}");
            variables.Set("OctopusFunctionAppenderTargetScriptParameters", script.Parameters);
            var copyScriptFile = variables.Get(ScriptFunctionsVariables.CopyScriptWrapper);
            var scriptFile     = CreateContextScriptFile(workingDirectory, scriptSyntax);

            if (!String.IsNullOrEmpty(copyScriptFile))
            {
                var destinationFile = copyScriptFile;
                if (!Path.IsPathRooted(copyScriptFile))
                {
                    destinationFile = Path.Combine(workingDirectory, copyScriptFile);
                }

                File.Copy(scriptFile, destinationFile, true);
            }

            using (var contextScriptFile = new TemporaryFile(scriptFile))
            {
                return(NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars));
            }
        }
Exemplo n.º 4
0
        string GetFetchScript(string workingDirectory, ScriptSyntax syntax)
        {
            AssemblyEmbeddedResources embeddedResources = new AssemblyEmbeddedResources();
            string contextFile;

            switch (syntax)
            {
            case ScriptSyntax.Bash:
                contextFile = "helmFetch.sh";
                break;

            case ScriptSyntax.PowerShell:
                contextFile = "HelmFetch.ps1";
                break;

            default:
                throw new InvalidOperationException("No kubernetes context wrapper exists for " + syntax);
            }

            var k8sContextScriptFile = Path.Combine(workingDirectory, $"Octopus.{contextFile}");
            var contextScript        = embeddedResources.GetEmbeddedResourceText(Assembly.GetExecutingAssembly(), $"Calamari.Integration.Packages.Download.Scripts.{contextFile}");

            fileSystem.OverwriteFile(k8sContextScriptFile, contextScript);
            return(k8sContextScriptFile);
        }
Exemplo n.º 5
0
 public static string FileExtension(this ScriptSyntax scriptSyntax)
 {
     return(typeof(ScriptSyntax).GetField(scriptSyntax.ToString())
            .GetCustomAttributes(typeof(FileExtensionAttribute), false)
            .Select(attr => ((FileExtensionAttribute)attr).Extension)
            .FirstOrDefault());
 }
Exemplo n.º 6
0
        /// <summary>
        /// Script wrappers form a chain, with one wrapper calling the next, much like
        /// a linked list. The last wrapper to be called is the TerminalScriptWrapper,
        /// which simply executes a ScriptEngine without any additional processing.
        /// In this way TerminalScriptWrapper is what actually executes the script
        /// that is to be run, with all other wrappers contributing to the script
        /// context.
        /// </summary>
        /// <param name="scriptSyntax">The type of the script being run</param>
        /// <param name="variables"></param>
        /// <returns>
        /// The start of the wrapper chain. Because each IScriptWrapper is expected to call its NextWrapper,
        /// calling ExecuteScript() on the start of the chain will result in every part of the chain being
        /// executed, down to the final TerminalScriptWrapper.
        /// </returns>
        IScriptWrapper BuildWrapperChain(ScriptSyntax scriptSyntax, IVariables variables) =>
        // get the type of script
        scriptWrapperHooks
        .Where(hook => hook.IsEnabled(scriptSyntax))

        /*
         * Sort the list in descending order of priority to ensure that
         * authentication script wrappers are called before any tool
         * script wrapper that might rely on the auth having being performed
         */
        .OrderByDescending(hook => hook.Priority)
        .Aggregate(
            // The last wrapper is always the TerminalScriptWrapper
            new TerminalScriptWrapper(GetScriptExecutor(scriptSyntax), variables),
            (IScriptWrapper current, IScriptWrapper next) =>
        {
            // the next wrapper is pointed to the current one
            next.NextWrapper = current;

            /*
             * The next wrapper is carried across to the next aggregate call,
             * or is returned as the result of the aggregate call. This means
             * the last item in the list is the return value.
             */
            return(next);
        });
Exemplo n.º 7
0
        void SetExecutable(RunningDeployment deployment, StringBuilder sb, ScriptSyntax syntax)
        {
            var helmExecutable = deployment.Variables.Get(SpecialVariables.Helm.CustomHelmExecutable);

            if (!string.IsNullOrWhiteSpace(helmExecutable))
            {
                if (deployment.Variables.GetIndexes(Deployment.SpecialVariables.Packages.PackageCollection)
                    .Contains(SpecialVariables.Helm.Packages.CustomHelmExePackageKey) && !Path.IsPathRooted(helmExecutable))
                {
                    helmExecutable = Path.Combine(SpecialVariables.Helm.Packages.CustomHelmExePackageKey, helmExecutable);
                    Log.Info(
                        $"Using custom helm executable at {helmExecutable} from inside package. Full path at {Path.GetFullPath(helmExecutable)}");
                }
                else
                {
                    Log.Info($"Using custom helm executable at {helmExecutable}");
                }

                // With PowerShell we need to invoke custom executables
                sb.Append(syntax == ScriptSyntax.PowerShell ? ". " : $"chmod +x \"{helmExecutable}\"\n");
                sb.Append($"\"{helmExecutable}\"");
            }
            else
            {
                sb.Append("helm");
            }
        }
        string BuildHelmCommand(RunningDeployment deployment, ScriptSyntax syntax)
        {
            var releaseName = GetReleaseName(deployment.Variables);
            var packagePath = GetChartLocation(deployment);

            var customHelmExecutable = CustomHelmExecutableFullPath(deployment.Variables, deployment.CurrentDirectory);
            var helmVersion          = GetVersion(deployment.Variables);

            CheckHelmToolVersion(customHelmExecutable, helmVersion);

            var sb = new StringBuilder();

            SetExecutable(sb, syntax, customHelmExecutable);
            sb.Append($" upgrade --install");
            SetNamespaceParameter(deployment, sb);
            SetResetValuesParameter(deployment, sb);
            if (helmVersion == HelmVersion.V2)
            {
                SetTillerTimeoutParameter(deployment, sb);
                SetTillerNamespaceParameter(deployment, sb);
            }

            SetTimeoutParameter(deployment, sb);
            SetValuesParameters(deployment, sb);
            SetAdditionalArguments(deployment, sb);
            sb.Append($" \"{releaseName}\" \"{packagePath}\"");

            log.Verbose(sb.ToString());
            return(sb.ToString());
        }
        /// <summary>
        /// One of these fields must be present for a k8s step
        /// </summary>
        public bool IsEnabled(ScriptSyntax syntax)
        {
            var hasClusterUrl  = !string.IsNullOrEmpty(variables.Get(SpecialVariables.ClusterUrl));
            var hasClusterName = !string.IsNullOrEmpty(variables.Get(SpecialVariables.AksClusterName)) || !string.IsNullOrEmpty(variables.Get(SpecialVariables.EksClusterName)) || !string.IsNullOrEmpty(variables.Get(SpecialVariables.GkeClusterName));

            return(hasClusterUrl || hasClusterName);
        }
Exemplo n.º 10
0
 public CommandResult ExecuteScript(Script script,
                                    ScriptSyntax scriptSyntax,
                                    ICommandLineRunner commandLineRunner,
                                    Dictionary <string, string> environmentVars)
 {
     WasCalled = true;
     return(NextWrapper.ExecuteScript(script, scriptSyntax, commandLineRunner, environmentVars));
 }
Exemplo n.º 11
0
        public bool IsEnabled(ScriptSyntax syntax)
        {
            if (String.IsNullOrEmpty(variables.Get(ScriptFunctionsVariables.Registration)))
            {
                return(false);
            }

            return(codeGenFunctionsRegistry.SupportedScriptSyntax.Contains(syntax));
        }
Exemplo n.º 12
0
 public CommandResult ExecuteScript(Script script,
                                    ScriptSyntax scriptSyntax,
                                    CalamariVariableDictionary variables,
                                    ICommandLineRunner commandLineRunner,
                                    StringDictionary environmentVars)
 {
     WasCalled = true;
     return(NextWrapper.ExecuteScript(script, scriptSyntax, variables, commandLineRunner, environmentVars));
 }
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           CalamariVariableDictionary variables,
                                           ICommandLineRunner commandLineRunner,
                                           StringDictionary environmentVars)
        {
            // We only execute this hook if the connection endpoint has been set
            if (!IsEnabled(scriptSyntax))
            {
                throw new InvalidOperationException(
                          "This script wrapper hook is not enabled, and should not have been run");
            }

            if (!ServiceFabricHelper.IsServiceFabricSdkKeyInRegistry())
            {
                throw new Exception("Could not find the Azure Service Fabric SDK on this server. This SDK is required before running Service Fabric commands.");
            }

            var workingDirectory = Path.GetDirectoryName(script.File);

            variables.Set("OctopusFabricTargetScript", "\"" + script.File + "\"");
            variables.Set("OctopusFabricTargetScriptParameters", script.Parameters);

            // Azure PS modules are required for looking up Azure environments (needed for AAD url lookup in Service Fabric world).
            SetAzureModulesLoadingMethod(variables);

            // Read thumbprint from our client cert variable (if applicable).
            var securityMode         = variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode);
            var clientCertThumbprint = string.Empty;

            if (securityMode == AzureServiceFabricSecurityMode.SecureClientCertificate.ToString())
            {
                var certificateVariable = GetMandatoryVariable(variables, SpecialVariables.Action.ServiceFabric.ClientCertVariable);
                clientCertThumbprint = variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Thumbprint}");
            }

            // Set output variables for our script to access.
            SetOutputVariable("OctopusFabricConnectionEndpoint", variables.Get(SpecialVariables.Action.ServiceFabric.ConnectionEndpoint), variables);
            SetOutputVariable("OctopusFabricSecurityMode", variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode), variables);
            SetOutputVariable("OctopusFabricServerCertThumbprint", variables.Get(SpecialVariables.Action.ServiceFabric.ServerCertThumbprint), variables);
            SetOutputVariable("OctopusFabricClientCertThumbprint", clientCertThumbprint, variables);
            SetOutputVariable("OctopusFabricCertificateFindType", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateFindType, "FindByThumbprint"), variables);
            SetOutputVariable("OctopusFabricCertificateFindValueOverride", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateFindValueOverride), variables);
            SetOutputVariable("OctopusFabricCertificateStoreLocation", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreLocation, "LocalMachine"), variables);
            SetOutputVariable("OctopusFabricCertificateStoreName", variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreName, "MY"), variables);
            SetOutputVariable("OctopusFabricAadCredentialType", variables.Get(SpecialVariables.Action.ServiceFabric.AadCredentialType), variables);
            SetOutputVariable("OctopusFabricAadClientCredentialSecret", variables.Get(SpecialVariables.Action.ServiceFabric.AadClientCredentialSecret), variables);
            SetOutputVariable("OctopusFabricAadUserCredentialUsername", variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialUsername), variables);
            SetOutputVariable("OctopusFabricAadUserCredentialPassword", variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialPassword), variables);

            using (new TemporaryFile(Path.Combine(workingDirectory, "AzureProfile.json")))
                using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory)))
                {
                    return(NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, variables, commandLineRunner, environmentVars));
                }
        }
Exemplo n.º 14
0
        public void ShouldBeEnabled(string connectionEndpoint, ScriptSyntax syntax, bool expected)
        {
            var variables = new CalamariVariables();

            variables.Add(SpecialVariables.Action.ServiceFabric.ConnectionEndpoint, connectionEndpoint);
            var target = new AzureServiceFabricPowerShellContext(variables);
            var actual = target.IsEnabled(syntax);

            actual.Should().Be(expected);
        }
Exemplo n.º 15
0
        string CreateContextScriptFile(string workingDirectory, ScriptSyntax scriptSyntax)
        {
            var registrations = variables.Get(ScriptFunctionsVariables.Registration);
            var results       = JsonConvert.DeserializeObject <IList <ScriptFunctionRegistration> >(registrations);

            var azureContextScriptFile = Path.Combine(workingDirectory, $"Octopus.FunctionAppenderContext.{scriptSyntax.FileExtension()}");
            var contextScript          = codeGenFunctionsRegistry.GetCodeGenerator(scriptSyntax).Generate(results);

            fileSystem.OverwriteFile(azureContextScriptFile, contextScript);
            return(azureContextScriptFile);
        }
Exemplo n.º 16
0
        public void ShouldBeEnabled(string accountType, string connectionEndpoint, ScriptSyntax syntax, bool expected)
        {
            var variables = new CalamariVariableDictionary
            {
                { SpecialVariables.Account.AccountType, accountType },
                { SpecialVariables.Action.ServiceFabric.ConnectionEndpoint, connectionEndpoint }
            };
            var target = new AzurePowerShellContext(variables);
            var actual = target.IsEnabled(syntax);

            actual.Should().Be(expected);
        }
Exemplo n.º 17
0
        public static bool TryParse(TokenStack tokens, out Script script)
        {
            var scriptSyntax = new ScriptSyntax();

            if (scriptSyntax.TryParse(tokens, out GraphNode scriptNode))
            {
                script = (Script)scriptNode;
                return(true);
            }

            script = null;
            return(false);
        }
Exemplo n.º 18
0
 void SetExecutable(StringBuilder sb, ScriptSyntax syntax, string customHelmExecutable)
 {
     if (customHelmExecutable != null)
     {
         // With PowerShell we need to invoke custom executables
         sb.Append(syntax == ScriptSyntax.PowerShell ? ". " : $"chmod +x \"{customHelmExecutable}\"\n");
         sb.Append($"\"{customHelmExecutable}\"");
     }
     else
     {
         sb.Append("helm");
     }
 }
Exemplo n.º 19
0
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           ICommandLineRunner commandLineRunner,
                                           Dictionary <string, string> environmentVars)
        {
            var awsEnvironmentVars = AwsEnvironmentGeneration.Create(log, variables).GetAwaiter().GetResult().EnvironmentVars;

            awsEnvironmentVars.AddRange(environmentVars);

            return(NextWrapper.ExecuteScript(
                       script, scriptSyntax,
                       commandLineRunner,
                       awsEnvironmentVars));
        }
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           ICommandLineRunner commandLineRunner,
                                           Dictionary <string, string> environmentVars)
        {
            // Only run this hook if we have an azure account
            if (!IsEnabled(scriptSyntax))
            {
                throw new InvalidOperationException(
                          "This script wrapper hook is not enabled, and should not have been run");
            }

            var workingDirectory = Path.GetDirectoryName(script.File);

            variables.Set("OctopusAzureTargetScript", $"{script.File}");
            variables.Set("OctopusAzureTargetScriptParameters", script.Parameters);

            SetOutputVariable(SpecialVariables.Action.Azure.Output.SubscriptionId, variables.Get(SpecialVariables.Action.Azure.SubscriptionId), variables);
            SetOutputVariable("OctopusAzureStorageAccountName", variables.Get(SpecialVariables.Action.Azure.StorageAccountName), variables);
            var azureEnvironment = variables.Get(SpecialVariables.Action.Azure.Environment, DefaultAzureEnvironment);

            if (azureEnvironment != DefaultAzureEnvironment)
            {
                Log.Info("Using Azure Environment override - {0}", azureEnvironment);
            }
            SetOutputVariable("OctopusAzureEnvironment", azureEnvironment, variables);

            SetOutputVariable("OctopusAzureExtensionsDirectory",
                              variables.Get(SpecialVariables.Action.Azure.ExtensionsDirectory), variables);

            using (new TemporaryFile(Path.Combine(workingDirectory, "AzureProfile.json")))
                using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory, scriptSyntax)))
                {
                    if (variables.Get(SpecialVariables.Account.AccountType) == "AzureServicePrincipal")
                    {
                        SetOutputVariable("OctopusUseServicePrincipal", true.ToString(), variables);
                        SetOutputVariable("OctopusAzureADTenantId", variables.Get(SpecialVariables.Action.Azure.TenantId), variables);
                        SetOutputVariable("OctopusAzureADClientId", variables.Get(SpecialVariables.Action.Azure.ClientId), variables);
                        variables.Set("OctopusAzureADPassword", variables.Get(SpecialVariables.Action.Azure.Password));
                        return(NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars));
                    }

                    //otherwise use management certificate
                    SetOutputVariable("OctopusUseServicePrincipal", false.ToString(), variables);
                    using (new TemporaryFile(CreateAzureCertificate(workingDirectory, variables)))
                    {
                        return(NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars));
                    }
                }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Script wrappers form a chain, with one wrapper calling the next, much like
 /// a linked list. The last wrapper to be called is the TerminalScriptWrapper,
 /// which simply executes a ScriptEngine without any additional processing.
 /// In this way TerminalScriptWrapper is what actually executes the script
 /// that is to be run, with all other wrappers contributing to the script
 /// context.
 /// </summary>
 /// <param name="scriptSyntax">The type of the script being run</param>
 /// <returns>
 /// The start of the wrapper chain. Because each IScriptWrapper is expected to call its NextWrapper,
 /// calling ExecuteScript() on the start of the chain will result in every part of the chain being
 /// executed, down to the final TerminalScriptWrapper.
 /// </returns>
 IScriptWrapper BuildWrapperChain(ScriptSyntax scriptSyntax) =>
 // get the type of script
 scriptWrapperHooks
 .Where(hook => hook.Enabled)
 .Aggregate(
     // The last wrapper is always the TerminalScriptWrapper
     new TerminalScriptWrapper(ScriptEngineRegistry.Instance.ScriptEngines[scriptSyntax]),
     (IScriptWrapper current, IScriptWrapper next) =>
 {
     // the next wrapper is pointed to the current one
     next.NextWrapper = current;
     // the next wrapper is carried across to the next aggregate call
     return(next);
 });
Exemplo n.º 22
0
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           CalamariVariableDictionary variables,
                                           ICommandLineRunner commandLineRunner,
                                           StringDictionary environmentVars)
        {
            var awsEnvironmentVars = AwsEnvironmentGeneration.Create(variables).GetAwaiter().GetResult().EnvironmentVars;

            return(NextWrapper.ExecuteScript(
                       script, scriptSyntax,
                       variables,
                       commandLineRunner,
                       environmentVars.MergeDictionaries(awsEnvironmentVars)));
        }
 public SetupKubectlAuthentication(IVariables variables,
                                   ILog log,
                                   ScriptSyntax scriptSyntax,
                                   ICommandLineRunner commandLineRunner,
                                   Dictionary <string, string> environmentVars,
                                   string workingDirectory)
 {
     this.variables         = variables;
     this.log               = log;
     this.scriptSyntax      = scriptSyntax;
     this.commandLineRunner = commandLineRunner;
     this.environmentVars   = environmentVars;
     this.workingDirectory  = workingDirectory;
 }
Exemplo n.º 24
0
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           ICommandLineRunner commandLineRunner,
                                           Dictionary <string, string> environmentVars)
        {
            var workingDirectory = Path.GetDirectoryName(script.File);

            variables.Set("OctopusKubernetesTargetScript", $"{script.File}");
            variables.Set("OctopusKubernetesTargetScriptParameters", script.Parameters);
            variables.Set("Octopus.Action.Kubernetes.KubectlConfig", Path.Combine(workingDirectory, "kubectl-octo.yml"));

            using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory, scriptSyntax)))
            {
                return(NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars));
            }
        }
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           ICommandLineRunner commandLineRunner,
                                           Dictionary <string, string> environmentVars)
        {
            var workingDirectory = Path.GetDirectoryName(script.File);

            if (environmentVars == null)
            {
                environmentVars = new Dictionary <string, string>();
            }

            var setupKubectlAuthentication = new SetupKubectlAuthentication(variables,
                                                                            log,
                                                                            scriptSyntax,
                                                                            commandLineRunner,
                                                                            environmentVars,
                                                                            workingDirectory);
            var accountType = variables.Get("Octopus.Account.AccountType");

            try
            {
                var result = setupKubectlAuthentication.Execute(accountType);

                if (result.ExitCode != 0)
                {
                    return(result);
                }
            }
            catch (CommandLineException)
            {
                return(new CommandResult(String.Empty, 1));
            }

            if (scriptSyntax == ScriptSyntax.PowerShell && accountType == "AzureServicePrincipal")
            {
                variables.Set("OctopusKubernetesTargetScript", $"{script.File}");
                variables.Set("OctopusKubernetesTargetScriptParameters", script.Parameters);

                using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory)))
                {
                    return(NextWrapper.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars));
                }
            }

            return(NextWrapper.ExecuteScript(script, scriptSyntax, commandLineRunner, environmentVars));
        }
Exemplo n.º 26
0
        public static string GetExtension(this ScriptSyntax syntax)
        {
            switch (syntax)
            {
            case ScriptSyntax.PowerShell:
                return("ps1");

            case ScriptSyntax.Bash:
                return("sh");

            case ScriptSyntax.CSharp:
                return("csx");

            case ScriptSyntax.FSharp:
                return("fsx");

            default:
                throw new ArgumentOutOfRangeException("syntax");
            }
        }
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           ICommandLineRunner commandLineRunner,
                                           Dictionary <string, string>?environmentVars)
        {
            var workingDirectory = Path.GetDirectoryName(script.File) !;

            variables.Set("OctopusAzureTargetScript", script.File);
            variables.Set("OctopusAzureTargetScriptParameters", script.Parameters);

            SetOutputVariable("OctopusAzureSubscriptionId", variables.Get(SpecialVariables.Action.Azure.SubscriptionId) !);
            SetOutputVariable("OctopusAzureStorageAccountName", variables.Get(SpecialVariables.Action.Azure.StorageAccountName) !);
            var azureEnvironment = variables.Get(SpecialVariables.Action.Azure.Environment, DefaultAzureEnvironment) !;

            if (azureEnvironment != DefaultAzureEnvironment)
            {
                log.InfoFormat("Using Azure Environment override - {0}", azureEnvironment);
            }
            SetOutputVariable("OctopusAzureEnvironment", azureEnvironment);
            SetOutputVariable("OctopusAzureExtensionsDirectory", variables.Get(SpecialVariables.Action.Azure.ExtensionsDirectory) !);

            using (new TemporaryFile(Path.Combine(workingDirectory, "AzureProfile.json")))
                using (var contextScriptFile = new TemporaryFile(CreateContextScriptFile(workingDirectory, scriptSyntax)))
                {
                    if (variables.Get(SpecialVariables.Account.AccountType) == "AzureServicePrincipal")
                    {
                        SetOutputVariable("OctopusUseServicePrincipal", bool.TrueString);
                        SetOutputVariable("OctopusAzureADTenantId", variables.Get(SpecialVariables.Action.Azure.TenantId) !);
                        SetOutputVariable("OctopusAzureADClientId", variables.Get(SpecialVariables.Action.Azure.ClientId) !);
                        variables.Set("OctopusAzureADPassword", variables.Get(SpecialVariables.Action.Azure.Password));
                        return(NextWrapper !.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars));
                    }

                    //otherwise use management certificate
                    SetOutputVariable("OctopusUseServicePrincipal", false.ToString());
                    using (new TemporaryFile(CreateAzureCertificate(workingDirectory)))
                    {
                        return(NextWrapper !.ExecuteScript(new Script(contextScriptFile.FilePath), scriptSyntax, commandLineRunner, environmentVars));
                    }
                }
        }
Exemplo n.º 28
0
        string BuildHelmCommand(RunningDeployment deployment, ScriptSyntax syntax)
        {
            var releaseName = GetReleaseName(deployment.Variables);
            var packagePath = GetChartLocation(deployment);

            var sb = new StringBuilder();

            SetExecutable(deployment, sb, syntax);
            sb.Append($" upgrade --install");
            SetNamespaceParameter(deployment, sb);
            SetResetValuesParameter(deployment, sb);
            SetTillerTimeoutParameter(deployment, sb);
            SetTillerNamespaceParameter(deployment, sb);
            SetTimeoutParameter(deployment, sb);
            SetValuesParameters(deployment, sb);
            SetAdditionalArguments(deployment, sb);
            sb.Append($" \"{releaseName}\" \"{packagePath}\"");

            Log.Verbose(sb.ToString());
            return(sb.ToString());
        }
Exemplo n.º 29
0
        IScriptExecutor GetScriptExecutor(ScriptSyntax scriptSyntax)
        {
            switch (scriptSyntax)
            {
            case ScriptSyntax.PowerShell:
                return(new PowerShellScriptExecutor());

            case ScriptSyntax.CSharp:
                return(new ScriptCSScriptExecutor());

            case ScriptSyntax.Bash:
                return(new BashScriptExecutor());

            case ScriptSyntax.FSharp:
                return(new FSharpExecutor());

            case ScriptSyntax.Python:
                return(new PythonScriptExecutor());

            default:
                throw new NotSupportedException($"{scriptSyntax} script are not supported for execution");
            }
        }
        string CreateContextScriptFile(string workingDirectory, ScriptSyntax syntax)
        {
            string contextFile;

            switch (syntax)
            {
            case ScriptSyntax.Bash:
                contextFile = "KubectlBashContext.sh";
                break;

            case ScriptSyntax.PowerShell:
                contextFile = "KubectlPowershellContext.ps1";
                break;

            default:
                throw new InvalidOperationException("No kubernetes context wrapper exists for " + syntax);
            }

            var k8sContextScriptFile = Path.Combine(workingDirectory, $"Octopus.{contextFile}");
            var contextScript        = embeddedResources.GetEmbeddedResourceText(Assembly.GetExecutingAssembly(), $"Calamari.Kubernetes.Scripts.{contextFile}");

            fileSystem.OverwriteFile(k8sContextScriptFile, contextScript);
            return(k8sContextScriptFile);
        }
Exemplo n.º 31
0
 public static InlineScriptAction InlineScript(ScriptSyntax syntax, string scriptBody)
 {
     return new InlineScriptAction(syntax, scriptBody);
 }
Exemplo n.º 32
0
 public InlineScriptAction(ScriptSyntax syntax, string scriptBody)
 {
     this.scriptBody = scriptBody;
     Syntax = syntax;
 }
Exemplo n.º 33
0
 ScriptSyntaxMeta(ScriptSyntax scriptSyntax, string extension, string name)
 {
     ScriptSyntax = scriptSyntax;
     Extension = extension;
     Name = name;
 }