public void ShouldDeployInParallel()
        {
            var extractionDirectories = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            var errors = new List <Exception>();

            using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0")))
            {
                var threads = Enumerable.Range(0, 4).Select(i => new Thread(new ThreadStart(delegate
                {
                    try
                    {
                        CalamariResult result;
                        using (var variablesFile = new TemporaryFile(Path.GetTempFileName()))
                        {
                            variables.Save(variablesFile.FilePath);

                            result = Invoke(Calamari()
                                            .Action("deploy-package")
                                            .Argument("package", acmeWeb.FilePath)
                                            .Argument("variables", variablesFile.FilePath));
                        }

                        result.AssertZero();
                        var extracted = result.GetOutputForLineContaining("Extracting package to: ");
                        result.AssertOutput("Extracted 7 files");
                        lock (extractionDirectories)
                        {
                            if (!extractionDirectories.Contains(extracted))
                            {
                                extractionDirectories.Add(extracted);
                            }
                            else
                            {
                                Assert.Fail("The same installation directory was used twice: " + extracted);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        errors.Add(ex);
                    }
                }))).ToList();

                foreach (var thread in threads)
                {
                    thread.Start();
                }
                foreach (var thread in threads)
                {
                    thread.Join();
                }
            }

            var allErrors = string.Join(Environment.NewLine, errors.Select(e => e.ToString()));

            Assert.That(allErrors, Is.EqualTo(""), allErrors);
        }
Example #2
0
        public void ShouldNotSubstituteVariablesInNonPackagedScript()
        {
            // Use a temp file for the script to avoid mutating the script file for other tests
            var scriptFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".ps1");

            File.WriteAllText(scriptFile, "Write-Host \"Hello #{Octopus.Environment.Name}!\"");

            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Octopus.Environment.Name", "Production");
            variables.Save(variablesFile);

            using (new TemporaryFile(scriptFile))
                using (new TemporaryFile(variablesFile))
                {
                    var output = Invoke(Calamari()
                                        .Action("run-script")
                                        .Argument("script", scriptFile)
                                        .Argument("variables", variablesFile));

                    output.AssertSuccess();
                    output.AssertOutput("Hello #{Octopus.Environment.Name}!");
                    AssertPSEdition(output);
                }
        }
Example #3
0
        public void ShouldCustomizePowerShellVersionIfRequested(string customPowerShellVersion, string expectedLogMessage)
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set(SpecialVariables.Action.PowerShell.CustomPowerShellVersion, customPowerShellVersion);
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                // Let's just use the Hello.ps1 script for something simples
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "Hello.ps1"))
                                    .Argument("variables", variablesFile));

                if (output.CapturedOutput.AllMessages
                    .Select(line => new string(line.ToCharArray().Where(c => c != '\u0000').ToArray()))
                    .Any(line => line.Contains(".NET Framework is not installed")))
                {
                    Assert.Inconclusive("Version 2.0 of PowerShell is not supported on this machine");
                }

                output.AssertSuccess();
                output.AssertOutput(expectedLogMessage);
                output.AssertOutput("Hello!");
            }
        }
Example #4
0
        public void ShouldCallWithNoProfileWhenVariableSet(string executeWithoutProfile, bool calledWithNoProfile)
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            if (executeWithoutProfile != null)
            {
                variables.Set(SpecialVariables.Action.PowerShell.ExecuteWithoutProfile, executeWithoutProfile);
            }
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "Profile.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                var allOutput = string.Join(Environment.NewLine, output.CapturedOutput.Infos);
                // Need to check for "-NoProfile -NoLogo" not just "-NoProfile" because when
                // run via Cake we end up with the outer Powershell call included in the
                // output too, which has a -NoProfile flag.
                Assert.That(allOutput.Contains("-NoProfile -NoLo") == calledWithNoProfile);
                AssertPSEdition(output);
            }
        }
        public void Deploy()
        {
            OctopusTestAzureSubscription.IgnoreIfCertificateNotInstalled();

            var nugetPackageFile = PackageBuilder.BuildSamplePackage("Octopus.Sample.AzureCloudService", "1.0.0");

            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            OctopusTestAzureSubscription.PopulateVariables(variables);
            OctopusTestCloudService.PopulateVariables(variables);
            variables.Set(SpecialVariables.Action.Azure.Slot, "Staging");
            variables.Set(SpecialVariables.Action.Azure.SwapIfPossible, false.ToString());
            variables.Set(SpecialVariables.Action.Azure.UseCurrentInstanceCount, false.ToString());

            variables.Set(SpecialVariables.Action.Name, "AzureCloudService");
            variables.Set(SpecialVariables.Release.Number, "1.0.0");

            // Disable cspkg extraction
            variables.Set(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled, true.ToString());

            fileSystem       = new WindowsPhysicalFileSystem();
            stagingDirectory = Path.GetTempPath();
            variables.Set(SpecialVariables.Action.Azure.PackageExtractionPath, stagingDirectory);

            variables.Save(variablesFile);

            result = Invoke(
                Calamari()
                .Action("deploy-azure-cloud-service")
                .Argument("package", nugetPackageFile)
                .Argument("variables", variablesFile));
        }
Example #6
0
        public void ShouldSubstituteVariablesInPackagedScripts()
        {
            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Octopus.Environment.Name", "Production");
            variables.Set(SpecialVariables.Action.Script.ScriptFileName, "Deploy.ps1");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("package", GetFixtureResouce("Packages", "PackagedScript.1.0.0.zip"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput("Extracting package");
                output.AssertOutput("Performing variable substitution");
                output.AssertOutput("OctopusParameter: Production");
                output.AssertOutput("InlineVariable: Production");
                output.AssertOutput("VariableSubstitution: Production");
                AssertPSEdition(output);
            }
        }
Example #7
0
        void CreateInSensitiveVariableFile()
        {
            var firstInsensitiveVariableSet = new VariableDictionary(firstInsensitiveVariablesFileName);

            firstInsensitiveVariableSet.Set("firstInsensitiveVariableName", "firstInsensitiveVariableValue");
            firstInsensitiveVariableSet.Save();
        }
        public void Deploy()
        {
            OctopusTestAzureSubscription.IgnoreIfCertificateNotInstalled();

            var nugetPackageFile = PackageBuilder.BuildSamplePackage("Octopus.Sample.AzureCloudService", "1.0.0");

            var variablesFile = Path.GetTempFileName();
            var variables = new VariableDictionary();
            OctopusTestAzureSubscription.PopulateVariables(variables);
            OctopusTestCloudService.PopulateVariables(variables);
            variables.Set(SpecialVariables.Action.Azure.Slot, "Staging");
            variables.Set(SpecialVariables.Action.Azure.SwapIfPossible, false.ToString());
            variables.Set(SpecialVariables.Action.Azure.UseCurrentInstanceCount, false.ToString());

            variables.Set(SpecialVariables.Action.Name, "AzureCloudService");
            variables.Set(SpecialVariables.Release.Number, "1.0.0");

            // Disable cspkg extraction
            variables.Set(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled, true.ToString());

            fileSystem = new WindowsPhysicalFileSystem();
            stagingDirectory = Path.GetTempPath();
            variables.Set(SpecialVariables.Action.Azure.PackageExtractionPath, stagingDirectory);

            variables.Save(variablesFile);

            result = Invoke(
                Calamari()
                    .Action("deploy-azure-cloud-service")
                    .Argument("package", nugetPackageFile)
                    .Argument("variables", variablesFile));
        }
Example #9
0
        public void ShouldSupportRoundTripping()
        {
            var temp = Path.GetTempFileName();

            var parent = new VariableDictionary();

            parent.Set("Name", "Web01");
            parent.Set("Port", "10933");
            parent.Set("Hello world", "This is a \"string\"!@#$");

            parent.Save(temp);

            var child = new VariableDictionary(temp);

            child["Name"].Should().Be("Web01");
            child["Port"].Should().Be("10933");
            child["Hello world"].Should().Be("This is a \"string\"!@#$");

            // Since this variable dictionary was loaded from disk, setting variables
            // will automatically persist the change
            child["SomeVariable"] = "Hello";

            parent["SomeVariable"].Should().BeNull();

            // If one process calls another (using the same variables file), the parent process should
            // reload its variables once the child finishes.
            parent.Reload();

            parent["SomeVariable"].Should().Be("Hello");

            File.Delete(temp);
        }
        private void CreateInSensitiveVariableFile()
        {
            var insensitiveVariables = new VariableDictionary(insensitiveVariablesFileName);

            insensitiveVariables.Set("insensitiveVariableName", "insensitiveVariableValue");
            insensitiveVariables.Save();
        }
Example #11
0
        public void ShouldNotSubstituteVariablesByDefault()
        {
            // Use a temp file for the script because the file would have been mutated by other tests
            var scriptFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".ps1");

            File.WriteAllText(scriptFile, "Write-Host \"Hello #{Octopus.Environment.Name}!\"");

            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Octopus.Environment.Name", "Production");
            variables.Save(variablesFile);

            using (new TemporaryFile(scriptFile))
                using (new TemporaryFile(variablesFile))
                {
                    var output = Invoke(Calamari()
                                        .Action("run-script")
                                        .Argument("script", scriptFile)
                                        .Argument("variables", variablesFile));

                    output.AssertZero();
                    output.AssertOutput("Hello #{Octopus.Environment.Name}!");
                }
        }
Example #12
0
        public void ShouldPrintVariables()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set("Variable1", "ABC");
            variables.Set("Variable2", "DEF");
            variables.Set("Variable3", "GHI");
            variables.Set("Foo_bar", "Hello");
            variables.Set("Host", "Never");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "PrintVariables.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput("V1= ABC");
                output.AssertOutput("V2= DEF");
                output.AssertOutput("V3= GHI");
                output.AssertOutput("FooBar= Hello");     // Legacy - '_' used to be removed
                output.AssertOutput("Foo_Bar= Hello");    // Current - '_' is valid in PowerShell
            }
        }
Example #13
0
        IEnumerable <string> ExecuteAndReturnLogOutput(Action <VariableDictionary> populateVariables, string folderName, params Type[] commandTypes)
        {
            void Copy(string sourcePath, string destinationPath)
            {
                foreach (var dirPath in Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
                }

                foreach (var newPath in Directory.EnumerateFiles(sourcePath, "*.*", SearchOption.AllDirectories))
                {
                    File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
                }
            }

            using (var currentDirectory = TemporaryDirectory.Create())
            {
                var variablesFile = Path.GetTempFileName();
                var variables     = new VariableDictionary();
                variables.Set(TerraformSpecialVariables.Calamari.TerraformCliPath, Path.GetDirectoryName(customTerraformExecutable));
                variables.Set(SpecialVariables.OriginalPackageDirectoryPath, currentDirectory.DirectoryPath);
                variables.Set(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable, customTerraformExecutable);

                populateVariables(variables);

                var terraformFiles = TestEnvironment.GetTestPath("Terraform", folderName);

                Copy(terraformFiles, currentDirectory.DirectoryPath);

                variables.Save(variablesFile);

                using (new TemporaryFile(variablesFile))
                {
                    foreach (var commandType in commandTypes)
                    {
                        var sb = new StringBuilder();
                        Log.StdOut = new IndentedTextWriter(new StringWriter(sb));

                        var command = (ICommand)Activator.CreateInstance(commandType);
                        var result  = command.Execute(new[] { "--variables", $"{variablesFile}" });

                        result.Should().Be(0);

                        var output = sb.ToString();

                        Console.WriteLine(output);

                        yield return(output);
                    }
                }
            }
        }
Example #14
0
        CalamariResult DeployPackage(string packageName)
        {
            using (var variablesFile = new TemporaryFile(Path.GetTempFileName()))
                using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageName, "1.0.0")))
                {
                    variables.Save(variablesFile.FilePath);

                    return(Invoke(Calamari()
                                  .Action("deploy-azure-web")
                                  .Argument("package", acmeWeb.FilePath)
                                  .Argument("variables", variablesFile.FilePath)));
                }
        }
Example #15
0
        CalamariResult ExecuteCommand(VariableDictionary variables, string extensions = "")
        {
            using (var variablesFile = new TemporaryFile(Path.GetTempFileName()))
            {
                variables.Save(variablesFile.FilePath);

                return(Invoke(Calamari()
                              .Action("execute-manifest")
                              .Argument("variables", variablesFile.FilePath)
                              .Argument("sensitiveVariablesPassword", "GB8KdBqYRlgAON9ISUPdnQ==")
                              .Argument("extensions", extensions)));
            }
        }
Example #16
0
        private int InvokeScript(CalamariVariableDictionary variables, VariableDictionary outputVariables)
        {
            if (!File.Exists(scriptFile))
                throw new CommandException("Could not find script file: " + scriptFile);

            var scriptEngine = new CombinedScriptEngine();
            var runner = new CommandLineRunner(
                new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables), new ServiceMessageCommandOutput(outputVariables)));
            var result = scriptEngine.Execute(scriptFile, variables, runner);

            outputVariables.Save();

            return result.ExitCode;
        }
Example #17
0
        string Upload(string packageName, List <S3FileSelectionProperties> fileSelections)
        {
            var bucketKeyPrefix = $"calamaritest/{Guid.NewGuid():N}/";

            fileSelections.ForEach(properties =>
            {
                if (properties is S3MultiFileSelectionProperties multiFileSelectionProperties)
                {
                    multiFileSelectionProperties.BucketKeyPrefix = bucketKeyPrefix;
                }

                if (properties is S3SingleFileSelectionProperties singleFileSelectionProperties)
                {
                    singleFileSelectionProperties.BucketKeyPrefix = bucketKeyPrefix;
                }
            });

            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount");
            variables.Set("AWSAccount.AccessKey", Environment.GetEnvironmentVariable("AWS_Calamari_Access"));
            variables.Set("AWSAccount.SecretKey", Environment.GetEnvironmentVariable("AWS_Calamari_Secret"));
            variables.Set("Octopus.Action.Aws.Region", RegionEndpoint.APSoutheast1.SystemName);
            variables.Set(AwsSpecialVariables.S3.FileSelections,
                          JsonConvert.SerializeObject(fileSelections, GetEnrichedSerializerSettings()));
            variables.Save(variablesFile);

            var packageDirectory = TestEnvironment.GetTestPath("AWS", "S3", packageName);

            using (var package =
                       new TemporaryFile(PackageBuilder.BuildSimpleZip(packageName, "1.0.0", packageDirectory)))
                using (new TemporaryFile(variablesFile))
                {
                    var command = new UploadAwsS3Command();
                    var result  = command.Execute(new[] {
                        "--package", $"{package.FilePath}",
                        "--variables", $"{variablesFile}",
                        "--bucket", BucketName,
                        "--targetMode", S3TargetMode.FileSelections.ToString()
                    });

                    result.Should().Be(0);
                }

            return(bucketKeyPrefix);
        }
        public void ShouldIncludeSensitiveVariables()
        {
            const string encryptionPassword = "******";

            var insensitiveVariables = new VariableDictionary(insensitiveVariablesFileName);
            insensitiveVariables.Set("insensitiveVariableName", "insensitiveVariableValue");
            insensitiveVariables.Save();

            var sensitiveVariables = new Dictionary<string, string>
            {
                {"sensitiveVariableName", "sensitiveVariableValue"}
            };
            var salt = CreateEncryptedSensitiveVariablesFile(sensitiveVariablesFileName, encryptionPassword, sensitiveVariables);

            var result = subject.IncludeSensitiveVariables(insensitiveVariablesFileName, encryptionPassword, salt);

            Assert.AreEqual("sensitiveVariableValue", result.Get("sensitiveVariableName"));
            Assert.AreEqual("insensitiveVariableValue", result.Get("insensitiveVariableName"));
        }
Example #19
0
        public void ShoulPassOnStdInfoWithTreatScriptWarningsAsErrors()
        {
            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Octopus.Action.FailScriptOnErrorOutput", "True");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("variables", variablesFile)
                                    .Argument("script", GetFixtureResouce("Scripts", "Hello.ps1")));

                output.AssertSuccess();
                output.AssertOutput("Hello!");
            }
        }
Example #20
0
        public void ShoulFailOnStdErrWithTreatScriptWarningsAsErrors()
        {
            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Octopus.Action.FailScriptOnErrorOutput", "True");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("sensitiveVariables", variablesFile)
                                    .Argument("script", GetFixtureResouce("Scripts", "stderr.sh")));

                output.AssertFailure();
                output.AssertErrorOutput("hello");
            }
        }
Example #21
0
        public void ShouldSupportModulesInVariables()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set("Octopus.Script.Module[Foo]", "function SayHello() { Write-Host \"Hello from module!\" }");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "UseModule.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput("Hello from module!");
            }
        }
        public void ShouldSetAzureSubscription()
        {
            // If the Azure test certificate is not installed, we cannot run, so ignore
            OctopusTestAzureSubscription.IgnoreIfCertificateNotInstalled();

            var variablesFile = Path.GetTempFileName();
            var variables = new VariableDictionary();
            variables.Set(SpecialVariables.Account.AccountType, "AzureSubscription");
            variables.Set(SpecialVariables.Account.Name, "AzureTest");
            variables.Save(variablesFile);
            OctopusTestAzureSubscription.PopulateVariables(variables);

            var output = Invoke(Calamari()
                .Action("run-script")
                .Argument("script", GetFixtureResouce("AzureSubscription.ps1"))
                .Argument("variables", variablesFile));

            output.AssertZero();
            output.AssertOutput("Current subscription ID: " + OctopusTestAzureSubscription.AzureSubscriptionId);
        }
Example #23
0
        protected CalamariResult TransferPackage()
        {
            var variables = new VariableDictionary
            {
                [SpecialVariables.Package.TransferPath]     = CustomDirectory,
                [SpecialVariables.Package.OriginalFileName] = Path.GetFileName(nupkgFile.FilePath),
                [SpecialVariables.Tentacle.CurrentDeployment.PackageFilePath] = nupkgFile.FilePath,
                [SpecialVariables.Action.Name]  = "MyAction",
                [SpecialVariables.Machine.Name] = "MyMachine"
            };

            using (var variablesFile = new TemporaryFile(Path.GetTempFileName()))
            {
                variables.Save(variablesFile.FilePath);

                return(Invoke(Calamari()
                              .Action("transfer-package")
                              .Argument("variables", variablesFile.FilePath)));
            }
        }
Example #24
0
        public void ShouldCallHelloDirectValue()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set("Name", "direct value");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "Hello.fsx"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput("Hello direct value");
            }
        }
Example #25
0
        public void ShouldNotCallWithNoProfileWhenVariableNotSet()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set(SpecialVariables.Action.PowerShell.ExecuteWithoutProfile, "true");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "Profile.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput("-NoProfile");
            }
        }
Example #26
0
        public void ShouldSetAzureSubscription()
        {
            // If the Azure test certificate is not installed, we cannot run, so ignore
            OctopusTestAzureSubscription.IgnoreIfCertificateNotInstalled();

            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set(SpecialVariables.Account.AccountType, "AzureSubscription");
            variables.Set(SpecialVariables.Account.Name, "AzureTest");
            variables.Save(variablesFile);
            OctopusTestAzureSubscription.PopulateVariables(variables);

            var output = Invoke(Calamari()
                                .Action("run-script")
                                .Argument("script", GetFixtureResouce("AzureSubscription.ps1"))
                                .Argument("variables", variablesFile));

            output.AssertZero();
            output.AssertOutput("Current subscription ID: " + OctopusTestAzureSubscription.AzureSubscriptionId);
        }
        public void ShouldAllowPlatformSpecificScriptToExecute()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.PowerShell), "Write-Host Hello Powershell");
            variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.CSharp), "Write-Host Hello CSharp");
            variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.Bash), "echo Hello Bash");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput(CalamariEnvironment.IsRunningOnWindows ? "Hello Powershell" : "Hello Bash");
            }
        }
Example #28
0
        public void ShouldFailIfAModuleHasASyntaxError()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set("Octopus.Script.Module[Foo]", "function SayHello() { Write-Host \"Hello from module! }");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "UseModule.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertFailure();
                output.AssertErrorOutput("ParserError", true);
                output.AssertErrorOutput("is missing the terminator", true);
            }
        }
Example #29
0
        public void ShouldRunBashInsteadOfPowerShell()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.PowerShell), "Write-Host Hello Powershell");
            variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.CSharp), "Write-Host Hello CSharp");
            variables.Set(SpecialVariables.Action.Script.ScriptBodyBySyntax(ScriptSyntax.Bash), "echo Hello Bash");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput("Hello Bash");
            }
        }
        public void ShouldShowFriendlyErrorWithInvalidSyntaxInScriptModule()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set("Octopus.Script.Module[Foo]", "function SayHello() { Write-Host \"Hello from module! }");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "UseModule.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertFailure();
                output.AssertOutput("Failed to import Script Module 'Foo'");
                output.AssertErrorOutput("Write-Host \"Hello from module!");
                output.AssertErrorOutput("The string is missing the terminator: \".");
            }
        }
Example #31
0
        public void ShouldCallHello()
        {
            var variablesFile = Path.GetTempFileName();
            var variables = new VariableDictionary();
            variables.Set("Name", "Paul");
            variables.Set("Variable2", "DEF");
            variables.Set("Variable3", "GHI");
            variables.Set("Foo_bar", "Hello");
            variables.Set("Host", "Never");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                    .Action("run-script")
                    .Argument("script", GetFixtureResouce("Scripts", "hello.sh"))
                    .Argument("variables", variablesFile));

                output.AssertZero();
                output.AssertOutput("Hello Paul");
            }
        }
Example #32
0
        public void ShouldCustomizePowerShellVersionIfRequested(string customPowerShellVersion, string expectedLogMessage)
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            variables.Set(SpecialVariables.Action.PowerShell.CustomPowerShellVersion, customPowerShellVersion);
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                // Let's just use the Hello.ps1 script for something simples
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "Hello.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput(expectedLogMessage);
                output.AssertOutput("Hello!");
            }
        }
Example #33
0
        protected (CalamariResult result, VariableDictionary variables) RunScript(string scriptName,
                                                                                  Dictionary <string, string> additionalVariables  = null,
                                                                                  Dictionary <string, string> additionalParameters = null,
                                                                                  string sensitiveVariablesPassword = null)
        {
            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set(SpecialVariables.Action.Script.ScriptFileName, scriptName);
            variables.Set(SpecialVariables.Action.Script.ScriptBody, File.ReadAllText(GetFixtureResouce("Scripts", scriptName)));
            variables.Set(SpecialVariables.Action.Script.Syntax, ScriptTypeExtensions.FileNameToScriptType(scriptName).ToString());

            additionalVariables?.ToList().ForEach(v => variables[v.Key] = v.Value);

            using (new TemporaryFile(variablesFile))
            {
                var cmdBase = Calamari()
                              .Action("run-script");

                if (sensitiveVariablesPassword == null)
                {
                    variables.Save(variablesFile);
                    cmdBase = cmdBase.Argument("variables", variablesFile);
                }
                else
                {
                    variables.SaveEncrypted(sensitiveVariablesPassword, variablesFile);
                    cmdBase = cmdBase.Argument("sensitiveVariables", variablesFile)
                              .Argument("sensitiveVariablesPassword", sensitiveVariablesPassword);
                }

                cmdBase = (additionalParameters ?? new Dictionary <string, string>()).Aggregate(cmdBase, (cmd, param) => cmd.Argument(param.Key, param.Value));

                var output = Invoke(cmdBase, variables);

                return(output, variables);
            }
        }
Example #34
0
        public void ShouldCallHello()
        {
            var variablesFile = Path.GetTempFileName();
            var variables     = new VariableDictionary();

            variables.Set("Name", "Paul");
            variables.Set("Variable2", "DEF");
            variables.Set("Variable3", "GHI");
            variables.Set("Foo_bar", "Hello");
            variables.Set("Host", "Never");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "hello.sh"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                output.AssertOutput("Hello Paul");
            }
        }
Example #35
0
        public void ShouldCallWithNoProfileWhenVariableSet(string executeWithoutProfile, bool calledWithNoProfile)
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();

            if (executeWithoutProfile != null)
            {
                variables.Set(SpecialVariables.Action.PowerShell.ExecuteWithoutProfile, executeWithoutProfile);
            }
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                                    .Action("run-script")
                                    .Argument("script", GetFixtureResouce("Scripts", "Profile.ps1"))
                                    .Argument("variables", variablesFile));

                output.AssertSuccess();
                var allOutput = string.Join(Environment.NewLine, output.CapturedOutput.Infos);
                Assert.That(allOutput.Contains("-NoProfile") == calledWithNoProfile);
            }
        }
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageFile, "No package file was specified. Please pass --package YourPackage.nupkg");

            if (!File.Exists(packageFile))
                throw new CommandException("Could not find package file: " + packageFile);

            Log.Info("Deploying package:    " + packageFile);

            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            var variables = new CalamariVariableDictionary(variablesFile, sensitiveVariablesFile, sensitiveVariablesPassword);
            var outputVariables = new VariableDictionary(outputVariablesFile);

            variables.MergeWith(outputVariables);

            var scriptCapability = new CombinedScriptEngine();
            var replacer = new ConfigurationVariablesReplacer(variables.GetFlag(SpecialVariables.Package.IgnoreVariableReplacementErrors));
            var substituter = new FileSubstituter(fileSystem);
            var configurationTransformer = new ConfigurationTransformer(variables.GetFlag(SpecialVariables.Package.IgnoreConfigTransformationErrors), variables.GetFlag(SpecialVariables.Package.SuppressConfigTransformationLogging));
            var embeddedResources = new CallingAssemblyEmbeddedResources();
            var iis = new InternetInformationServer();
            var commandLineRunner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables), new ServiceMessageCommandOutput(outputVariables)));
            var semaphore = new SystemSemaphore();
            var journal = new DeploymentJournal(fileSystem, semaphore, variables);

            var conventions = new List<IConvention>
            {
                new ContributeEnvironmentVariablesConvention(),
                new ContributePreviousInstallationConvention(journal),
                new LogVariablesConvention(),
                new AlreadyInstalledConvention(journal),
                new ExtractPackageToApplicationDirectoryConvention(new LightweightPackageExtractor(), fileSystem, semaphore),
                new FeatureScriptConvention(DeploymentStages.BeforePreDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PreDeploy, scriptCapability, fileSystem, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptCapability, commandLineRunner),
                new FeatureScriptConvention(DeploymentStages.AfterPreDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new SubstituteInFilesConvention(fileSystem, substituter),
                new ConfigurationTransformsConvention(fileSystem, configurationTransformer),
                new ConfigurationVariablesConvention(fileSystem, replacer),
                new CopyPackageToCustomInstallationDirectoryConvention(fileSystem),
                new FeatureScriptConvention(DeploymentStages.BeforeDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.Deploy, fileSystem, scriptCapability, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.Deploy, scriptCapability, fileSystem, commandLineRunner),
                new FeatureScriptConvention(DeploymentStages.AfterDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new LegacyIisWebSiteConvention(fileSystem, iis),
                new FeatureScriptConvention(DeploymentStages.BeforePostDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptCapability, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PostDeploy, scriptCapability, fileSystem, commandLineRunner),
                new FeatureScriptConvention(DeploymentStages.AfterPostDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
            };

            var deployment = new RunningDeployment(packageFile, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);

            try
            {
                conventionRunner.RunConventions();
                outputVariables.Save();

                if (!deployment.SkipJournal)
                    journal.AddJournalEntry(new JournalEntry(deployment, true));
            }
            catch (Exception)
            {
                if (!deployment.SkipJournal)
                    journal.AddJournalEntry(new JournalEntry(deployment, false));
                throw;
            }

            return 0;
        }
Example #37
0
        public void ShouldSupportModulesInVariables()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();
            variables.Set("Octopus.Script.Module[Foo]", "function SayHello() { Write-Host \"Hello from module!\" }");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                   .Action("run-script")
                   .Argument("script", GetFixtureResouce("Scripts", "UseModule.ps1"))
                   .Argument("variables", variablesFile));

                output.AssertZero();
                output.AssertOutput("Hello from module!");
            }
        }
Example #38
0
        public void ShouldPrintVariables()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new VariableDictionary();
            variables.Set("Variable1", "ABC");
            variables.Set("Variable2", "DEF");
            variables.Set("Variable3", "GHI");
            variables.Set("Foo_bar", "Hello");
            variables.Set("Host", "Never");
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var output = Invoke(Calamari()
                   .Action("run-script")
                   .Argument("script", GetFixtureResouce("Scripts", "PrintVariables.ps1"))
                   .Argument("variables", variablesFile));

                output.AssertZero();
                output.AssertOutput("V1= ABC");
                output.AssertOutput("V2= DEF");
                output.AssertOutput("V3= GHI");
                output.AssertOutput("FooBar= Hello");     // Legacy - '_' used to be removed
                output.AssertOutput("Foo_Bar= Hello");    // Current - '_' is valid in PowerShell
            }
        }
 private void CreateSensitiveVariableFile()
 {
     var insensitiveVariables = new VariableDictionary(insensitiveVariablesFileName);
     insensitiveVariables.Set("insensitiveVariableName", "insensitiveVariableValue");
     insensitiveVariables.Save();
 }