Exemple #1
0
        public void ShouldLogVariables()
        {
            var variables = new CalamariVariables();

            variables.Set(KnownVariables.PrintVariables, true.ToString());
            variables.Set(KnownVariables.PrintEvaluatedVariables, true.ToString());
            variables.Set(DeploymentEnvironment.Name, "Production");
            const string variableName     = "foo";
            const string rawVariableValue = "The environment is #{Octopus.Environment.Name}";

            variables.Set(variableName, rawVariableValue);

            var program = new TestProgram(new InMemoryLog());

            program.VariablesOverride = variables;
            program.RunStubCommand();

            var messages         = program.Log.Messages;
            var messagesAsString = string.Join(Environment.NewLine, program.Log.Messages.Select(m => m.FormattedMessage));

            //Assert raw variables were output
            messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == $"{KnownVariables.PrintVariables} is enabled. This should only be used for debugging problems with variables, and then disabled again for normal deployments.");
            messagesAsString.Should().Contain("The following variables are available:");
            messagesAsString.Should().Contain($"[{variableName}] = '{rawVariableValue}'");

            //Assert evaluated variables were output
            messages.Should().Contain(m => m.Level == InMemoryLog.Level.Warn && m.FormattedMessage == $"{KnownVariables.PrintEvaluatedVariables} is enabled. This should only be used for debugging problems with variables, and then disabled again for normal deployments.");
            messagesAsString.Should().Contain("The following evaluated variables are available:");
            messagesAsString.Should().Contain($"[{variableName}] = 'The environment is Production'");
        }
Exemple #2
0
        public void ShouldKeepExistingValues()
        {
            const string expected =
                @"{" +
                "  \"MyMessage\": \"Hello world!\"," +
                "  \"EmailSettings\": {" +
                "    \"SmtpPort\": \"24\"," +
                "    \"SmtpHost\": \"localhost\"," +
                "    \"DefaultRecipients\": {" +
                "      \"To\": \"[email protected]\"," +
                "      \"Cc\": \"[email protected]\"" +
                "    }" +
                "  }" +
                "}";

            var variables = new CalamariVariables();

            variables.Set("MyMessage", "Hello world!");
            variables.Set("EmailSettings:SmtpPort", "24");
            variables.Set("EmailSettings:DefaultRecipients:Cc", "*****@*****.**");

            var replaced = Replace(variables, existingFile: "appsettings.existing-expected.json");

            AssertJsonEquivalent(replaced, expected);
        }
Exemple #3
0
        public void ShouldReplaceInSimpleFile()
        {
            const string expected =
                @"{" +
                "  \"MyMessage\": \"Hello world\"," +
                "  \"EmailSettings\": {" +
                "    \"SmtpPort\": \"23\"," +
                "    \"SmtpHost\": \"localhost\"," +
                "    \"DefaultRecipients\": {" +
                "      \"To\": \"[email protected]\"," +
                "      \"Cc\": \"[email protected]\"" +
                "    }" +
                "  }" +
                "}";

            var variables = new CalamariVariables();

            variables.Set("MyMessage", "Hello world");
            variables.Set("EmailSettings:SmtpHost", "localhost");
            variables.Set("EmailSettings:SmtpPort", "23");
            variables.Set("EmailSettings:DefaultRecipients:To", "*****@*****.**");
            variables.Set("EmailSettings:DefaultRecipients:Cc", "*****@*****.**");

            var replaced = Replace(variables, existingFile: "appsettings.simple.json");

            AssertJsonEquivalent(replaced, expected);
        }
Exemple #4
0
        public void ShouldMatchAndReplaceIgnoringCase()
        {
            const string expected =
                @"{" +
                "  \"MyMessage\": \"Hello! world!\"," +
                "  \"EmailSettings\": {" +
                "    \"SmtpPort\": \"23\"," +
                "    \"SmtpHost\": \"localhost\"," +
                "    \"DefaultRecipients\": {" +
                "      \"To\": \"[email protected]\"," +
                "      \"Cc\": \"[email protected]\"" +
                "    }" +
                "  }" +
                "}";

            var variables = new CalamariVariables();

            variables.Set("mymessage", "Hello! world!");
            variables.Set("EmailSettings:Defaultrecipients:To", "*****@*****.**");
            variables.Set("EmailSettings:defaultRecipients:Cc", "*****@*****.**");

            var replaced = Replace(variables, existingFile: "appsettings.simple.json");

            AssertJsonEquivalent(replaced, expected);
        }
Exemple #5
0
        public void ShouldPerformSubstitutions()
        {
            string glob        = "**\\*config.json";
            string actualMatch = "config.json";


            var variables = new CalamariVariables();

            variables.Set(PackageVariables.SubstituteInFilesTargets, glob);
            variables.Set(PackageVariables.SubstituteInFilesEnabled, true.ToString());

            var deployment = new RunningDeployment(TestEnvironment.ConstructRootedPath("packages"), variables)
            {
                StagingDirectory = StagingDirectory
            };

            var fileSystem = Substitute.For <ICalamariFileSystem>();

            fileSystem.EnumerateFilesWithGlob(StagingDirectory, glob).Returns(new[] { Path.Combine(StagingDirectory, actualMatch) });

            var substituter = Substitute.For <IFileSubstituter>();

            new SubstituteInFiles(fileSystem, substituter, variables)
            .SubstituteBasedSettingsInSuppliedVariables(deployment);

            substituter.Received().PerformSubstitution(Path.Combine(StagingDirectory, actualMatch), variables);
        }
        public void DeleteStack(string stackName)
        {
            var variablesFile = Path.GetTempFileName();
            var variables     = new CalamariVariables();

            variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount");
            variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsAcessKey));
            variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsSecretKey));
            variables.Set("Octopus.Action.Aws.Region", region);
            variables.Set(AwsSpecialVariables.CloudFormation.StackName, stackName);
            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var log     = new InMemoryLog();
                var command = new DeleteCloudFormationCommand(
                    log,
                    variables
                    );
                var result = command.Execute(new[]
                {
                    "--variables", $"{variablesFile}",
                    "--waitForCompletion", "true"
                });

                result.Should().Be(0);
            }
        }
Exemple #7
0
        public void ShouldIgnoreOctopusPrefix()
        {
            const string expected =
                @"{" +
                "  \"MyMessage\": \"Hello world!\"," +
                "  \"IThinkOctopusIsGreat\": \"Yes, I do!\"," +
                "  \"OctopusRocks\": \"Yes it does\"," +
                "  \"Octopus\": {" +
                "    \"Section\": \"Should work\"," +
                "    \"Rocks\": \"is not changed\"," +
                "  }" +
                "}";

            var variables = new CalamariVariables();

            variables.Set("MyMessage", "Hello world!");
            variables.Set("IThinkOctopusIsGreat", "Yes, I do!");
            variables.Set("OctopusRocks", "This is ignored");
            variables.Set("Octopus.Rocks", "So is this");
            variables.Set("Octopus:Section", "Should work");

            var replaced = Replace(variables, existingFile: "appsettings.ignore-octopus.json");

            AssertJsonEquivalent(replaced, expected);
        }
Exemple #8
0
        protected CalamariVariables GetVariables()
        {
            var cd = new CalamariVariables();

            cd.Set("foo", "bar");
            cd.Set("mysecrect", "KingKong");
            return(cd);
        }
Exemple #9
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 CalamariVariables();

            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 log        = new InMemoryLog();
                    var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
                    var command    = new UploadAwsS3Command(
                        log,
                        variables,
                        fileSystem,
                        new SubstituteInFiles(fileSystem, new FileSubstituter(log, fileSystem), variables),
                        new ExtractPackage(new CombinedPackageExtractor(log), fileSystem, variables, log)
                        );
                    var result = command.Execute(new[] {
                        "--package", $"{package.FilePath}",
                        "--variables", $"{variablesFile}",
                        "--bucket", BucketName,
                        "--targetMode", S3TargetMode.FileSelections.ToString()
                    });

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

            return(bucketKeyPrefix);
        }
Exemple #10
0
        public void DoesNotAddXmlHeader()
        {
            var variables = new CalamariVariables();

            variables.Set("WelcomeMessage", "Hello world");
            variables.Set("LogFile", "C:\\Log.txt");
            variables.Set("DatabaseConnection", null);

            var text = PerformTest(GetFixtureResouce("Samples", "NoHeader.config"), variables);

            Assert.That(text, Does.StartWith("<configuration"));
        }
        public void ShouldPrioritizePowerShellScriptsOverOtherSyntaxes()
        {
            var variables = new CalamariVariables();

            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");

            var output = InvokeCalamariForPowerShell(calamari => calamari
                                                     .Action("run-script"), variables);

            output.AssertSuccess();
            output.AssertOutput("Hello PowerShell");
        }
Exemple #12
0
        public void ReplacesStronglyTypedAppSettings()
        {
            var variables = new CalamariVariables();

            variables.Set("WelcomeMessage", "Hello world");
            variables.Set("LogFile", "C:\\Log.txt");
            variables.Set("DatabaseConnection", null);

            var text = PerformTest(GetFixtureResouce("Samples", "StrongTyped.config"), variables);

            var contents = XDocument.Parse(text);

            Assert.AreEqual("Hello world", contents.XPathSelectElement("//AppSettings.Properties.Settings/setting[@name='WelcomeMessage']/value").Value);
        }
Exemple #13
0
        public void ReplacesConnectionStrings()
        {
            var variables = new CalamariVariables();

            variables.Set("MyDb1", "Server=foo");
            variables.Set("MyDb2", "Server=bar&bar=123");

            var text = PerformTest(GetFixtureResouce("Samples", "App.config"), variables);

            var contents = XDocument.Parse(text);

            Assert.AreEqual("Server=foo", contents.XPathSelectElement("//connectionStrings/add[@name='MyDb1']").Attribute("connectionString").Value);
            Assert.AreEqual("Server=bar&bar=123", contents.XPathSelectElement("//connectionStrings/add[@name='MyDb2']").Attribute("connectionString").Value);
        }
Exemple #14
0
        public async Task UploadPackage3()
        {
            var fileSelections = new List <S3TargetPropertiesBase>
            {
                new S3MultiFileSelectionProperties
                {
                    Pattern      = "*.json",
                    Type         = S3FileSelectionTypes.MultipleFiles,
                    StorageClass = "STANDARD",
                    CannedAcl    = "private",
                    StructuredVariableSubstitutionPatterns = "*.json"
                }
            };

            var variables = new CalamariVariables();

            variables.Set("Property1:Property2:Value", "InjectedValue");

            var prefix = Upload("Package3", fileSelections, variables);

            await Validate(async client =>
            {
                var file = await client.GetObjectAsync(bucketName, $"{prefix}file.json");
                var text = new StreamReader(file.ResponseStream).ReadToEnd();
                JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue");
            });
        }
Exemple #15
0
        public async Task UploadPackage3Complete()
        {
            var packageOptions = new List <S3TargetPropertiesBase>
            {
                new S3PackageOptions()
                {
                    StorageClass = "STANDARD",
                    CannedAcl    = "private",
                    StructuredVariableSubstitutionPatterns = "*.json",
                    BucketKeyBehaviour = BucketKeyBehaviourType.Filename,
                }
            };

            var variables = new CalamariVariables();

            variables.Set("Property1:Property2:Value", "InjectedValue");

            var prefix = Upload("Package3", packageOptions, variables, S3TargetMode.EntirePackage);

            await Validate(async client =>
            {
                var file         = await client.GetObjectAsync(bucketName, $"{prefix}Package3.1.0.0.zip");
                var memoryStream = new MemoryStream();
                await file.ResponseStream.CopyToAsync(memoryStream);
                var text = await new StreamReader(ZipArchive.Open(memoryStream).Entries.First(entry => entry.Key == "file.json").OpenEntryStream()).ReadToEndAsync();
                JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue");
            });
        }
Exemple #16
0
        public void CanDeserializeNestedVariable()
        {
            var          variables = new CalamariVariables();
            const string json      = @"[
                {""Identity"": ""#{UserName}"", ""Access"": ""FullControl""}
            ]";

            variables.Set("UserName", "AmericanEagles\\RogerRamjet");
            variables.Set(SpecialVariables.Certificate.PrivateKeyAccessRules, json);

            var result = ImportCertificateCommand.GetPrivateKeyAccessRules(variables).ToList();

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual("AmericanEagles\\RogerRamjet", result[0].Identity.ToString());
            Assert.AreEqual(PrivateKeyAccess.FullControl, result[0].Access);
        }
Exemple #17
0
        public void ReplacesAppSettings()
        {
            var variables = new CalamariVariables();

            variables.Set("WelcomeMessage", "Hello world");
            variables.Set("LogFile", "C:\\Log.txt");
            variables.Set("DatabaseConnection", null);

            var text = PerformTest(GetFixtureResouce("Samples", "App.config"), variables);

            var contents = XDocument.Parse(text);

            Assert.AreEqual("Hello world", contents.XPathSelectElement("//appSettings/add[@key='WelcomeMessage']").Attribute("value").Value);
            Assert.AreEqual("C:\\Log.txt", contents.XPathSelectElement("//appSettings/add[@key='LogFile']").Attribute("value").Value);
            Assert.AreEqual("", contents.XPathSelectElement("//appSettings/add[@key='DatabaseConnection']").Attribute("value").Value);
        }
Exemple #18
0
        public void ShouldReplacePropertyOfAnElementInArray()
        {
            const string expected =
                "{" +
                "  \"MyMessage\": \"Hello world\"," +
                "  \"EmailSettings\": {" +
                "    \"SmtpPort\": 23," +
                "    \"UseProxy\": false," +
                "    \"SmtpHost\": \"localhost\"," +
                "    \"DefaultRecipients\": [" +
                "        { " +
                "            \"Email\":\"[email protected]\"," +
                "            \"Name\": \"Paul\"" +
                "        }," +
                "        { " +
                "            \"Email\":\"[email protected]\"," +
                "            \"Name\": \"Mike\"" +
                "        }" +
                "    ]" +
                "  }" +
                "}";

            var variables = new CalamariVariables();

            variables.Set("EmailSettings:DefaultRecipients:1:Email", "*****@*****.**");

            var replaced = Replace(variables, existingFile: "appsettings.object-array.json");

            AssertJsonEquivalent(replaced, expected);
        }
Exemple #19
0
        public async Task UploadPackage3Individual()
        {
            var fileSelections = new List <S3TargetPropertiesBase>
            {
                new S3SingleFileSelectionProperties
                {
                    Path               = "file.json",
                    Type               = S3FileSelectionTypes.SingleFile,
                    StorageClass       = "STANDARD",
                    CannedAcl          = "private",
                    BucketKeyBehaviour = BucketKeyBehaviourType.Custom,
                    BucketKey          = "myfile.json",
                    PerformStructuredVariableSubstitution = true
                }
            };

            var variables = new CalamariVariables();

            variables.Set("Property1:Property2:Value", "InjectedValue");

            Upload("Package3", fileSelections, variables);

            await Validate(async client =>
            {
                var file = await client.GetObjectAsync(bucketName, $"myfile.json");
                var text = new StreamReader(file.ResponseStream).ReadToEnd();
                JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue");
            });
        }
Exemple #20
0
        public async Task SubstituteVariablesAndUploadZipArchives(string packageId, string packageVersion, string packageExtension)
        {
            var fileName = $"{packageId}.{packageVersion}.{packageExtension}";

            var packageOptions = new List <S3PackageOptions>
            {
                new S3PackageOptions
                {
                    StorageClass = "STANDARD",
                    CannedAcl    = "private",
                    StructuredVariableSubstitutionPatterns = "*.json",
                    BucketKeyBehaviour = BucketKeyBehaviourType.Filename,
                }
            };

            var variables = new CalamariVariables();

            variables.Set("Property1:Property2:Value", "InjectedValue");

            var packageFilePath = TestEnvironment.GetTestPath("AWS", "S3", "CompressedPackages", fileName);

            var prefix = UploadEntireCompressedPackage(packageFilePath, packageId, packageVersion, packageOptions, variables);

            await Validate(async client =>
            {
                var file         = await client.GetObjectAsync(bucketName, $"{prefix}{fileName}");
                var memoryStream = new MemoryStream();
                await file.ResponseStream.CopyToAsync(memoryStream);
                var text = await new StreamReader(ZipArchive.Open(memoryStream).Entries.First(entry => entry.Key == "file.json").OpenEntryStream()).ReadToEndAsync();
                JObject.Parse(text)["Property1"]["Property2"]["Value"].ToString().Should().Be("InjectedValue");
                memoryStream.Close();
            });
        }
Exemple #21
0
        [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426
        public void ShouldSuppressExceptionForTransformWarnings_WhenFlagIsSet()
        {
            var variables = new CalamariVariables();

            variables.Set(SpecialVariables.Package.TreatConfigTransformationWarningsAsErrors, "false");
            configurationTransformer = ConfigurationTransformer.FromVariables(variables, log);

            PerformTest(GetFixtureResource("Samples", "Web.config"), GetFixtureResource("Samples", "Web.Warning.config"));
        }
Exemple #22
0
        [RequiresMonoVersion423OrAbove] //Bug in mono < 4.2.3 https://bugzilla.xamarin.com/show_bug.cgi?id=19426
        public void ShouldSupressExceptionForBadConfig_WhenFlagIsSet()
        {
            var variables = new CalamariVariables();

            variables.Set(SpecialVariables.Package.IgnoreConfigTransformationErrors, "true");
            configurationTransformer = ConfigurationTransformer.FromVariables(variables, log);

            PerformTest(GetFixtureResource("Samples", "Bad.config"), GetFixtureResource("Samples", "Web.Release.config"));
        }
Exemple #23
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 variables = new CalamariVariables();
                variables.Set(TerraformSpecialVariables.Calamari.TerraformCliPath, Path.GetDirectoryName(customTerraformExecutable));
                variables.Set(KnownVariables.OriginalPackageDirectoryPath, currentDirectory.DirectoryPath);
                variables.Set(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable, customTerraformExecutable);

                populateVariables(variables);

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

                Copy(terraformFiles, currentDirectory.DirectoryPath);

                foreach (var commandType in commandTypes)
                {
                    var log     = new InMemoryLog();
                    var command = CreateInstance(commandType, variables, log);
                    var result  = command.Execute(new string[0]);

                    result.Should().Be(0);

                    var output = log.StandardOut.Join(Environment.NewLine);

                    Console.WriteLine(output);

                    yield return(output);
                }
            }
        }
Exemple #24
0
        protected string UploadEntireCompressedPackage(string packageFilePath, string packageId, string packageVersion, List <S3PackageOptions> propertiesList, VariableDictionary customVariables = null)
        {
            var bucketKeyPrefix = $"calamaritest/{Guid.NewGuid():N}/";
            var variables       = new CalamariVariables();

            propertiesList.ForEach(properties =>
            {
                properties.BucketKeyPrefix = bucketKeyPrefix;
                variables.Set(AwsSpecialVariables.S3.PackageOptions, JsonConvert.SerializeObject(properties, GetEnrichedSerializerSettings()));
                variables.Set(PackageVariables.PackageId, packageId);
                variables.Set(PackageVariables.PackageVersion, packageVersion);
            });

            var variablesFile = Path.GetTempFileName();

            variables.Set("Octopus.Action.AwsAccount.Variable", "AWSAccount");
            variables.Set("AWSAccount.AccessKey", ExternalVariables.Get(ExternalVariable.AwsAcessKey));
            variables.Set("AWSAccount.SecretKey", ExternalVariables.Get(ExternalVariable.AwsSecretKey));
            variables.Set("Octopus.Action.Aws.Region", region);

            if (customVariables != null)
            {
                variables.Merge(customVariables);
            }

            variables.Save(variablesFile);

            using (new TemporaryFile(variablesFile))
            {
                var log        = new InMemoryLog();
                var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

                var command = new UploadAwsS3Command(
                    log,
                    variables,
                    fileSystem,
                    new SubstituteInFiles(log, fileSystem, new FileSubstituter(log, fileSystem), variables),
                    new ExtractPackage(new CombinedPackageExtractor(log, variables, new CommandLineRunner(log, variables)), fileSystem, variables, log),
                    new StructuredConfigVariablesService(new PrioritisedList <IFileFormatVariableReplacer>
                {
                    new JsonFormatVariableReplacer(fileSystem, log),
                    new XmlFormatVariableReplacer(fileSystem, log),
                    new YamlFormatVariableReplacer(fileSystem, log),
                    new PropertiesFormatVariableReplacer(fileSystem, log),
                }, variables, fileSystem, log)
                    );

                var result = command.Execute(new[] {
                    "--package", $"{packageFilePath}",
                    "--variables", $"{variablesFile}",
                    "--bucket", bucketName,
                    "--targetMode", S3TargetMode.EntirePackage.ToString()
                });

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

            return(bucketKeyPrefix);
        }
        protected (CalamariResult result, IVariables variables) RunScript(string scriptName,
                                                                          Dictionary <string, string> additionalVariables  = null,
                                                                          Dictionary <string, string> additionalParameters = null,
                                                                          string sensitiveVariablesPassword = null,
                                                                          IEnumerable <string> extensions   = null)
        {
            var variablesFile = Path.GetTempFileName();
            var variables     = new CalamariVariables();

            variables.Set(ScriptVariables.ScriptFileName, scriptName);
            variables.Set(ScriptVariables.ScriptBody, File.ReadAllText(GetFixtureResource("Scripts", scriptName)));
            variables.Set(ScriptVariables.Syntax, scriptName.ToScriptType().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);
                }

                if (extensions != null)
                {
                    cmdBase.Argument("extensions", string.Join(",", extensions));
                }

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

                var output = Invoke(cmdBase, variables);

                return(output, variables);
            }
        }
Exemple #26
0
        public void ShouldSubstituteVariablesInPackagedScripts()
        {
            var variables = new CalamariVariables();

            variables.Set("Octopus.Environment.Name", "Production");
            variables.Set(ScriptVariables.ScriptFileName, "Deploy.ps1");

            var output = InvokeCalamariForPowerShell(calamari => calamari
                                                     .Action("run-script")
                                                     .Argument("package", GetFixtureResouce("Packages", "PackagedScript.1.0.0.zip")), variables);

            output.AssertSuccess();
            output.AssertOutput("Extracting package");
            output.AssertOutput("Performing variable substitution");
            output.AssertOutput("OctopusParameter: Production");
            output.AssertOutput("InlineVariable: Production");
            output.AssertOutput("VariableSubstitution: Production");
            AssertPowerShellEdition(output);
        }
Exemple #27
0
        public void SetUp()
        {
            var variables = new CalamariVariables();

            variables.Set(KnownVariables.OriginalPackageDirectoryPath, TestEnvironment.ConstructRootedPath("applications", "Acme", "1.0.0"));
            deployment = new RunningDeployment(TestEnvironment.ConstructRootedPath("Packages"), variables);
            configurationVariableReplacer = Substitute.For <IJsonConfigurationVariableReplacer>();
            fileSystem = Substitute.For <ICalamariFileSystem>();
            fileSystem.DirectoryExists(Arg.Any <string>()).Returns(false);
        }
Exemple #28
0
        void TestScript(IScriptWrapper wrapper, string scriptName)
        {
            using (var dir = TemporaryDirectory.Create())
                using (var temp = new TemporaryFile(Path.Combine(dir.DirectoryPath, scriptName)))
                {
                    File.WriteAllText(temp.FilePath, "kubectl get nodes");

                    var deploymentVariables = new CalamariVariables();
                    deploymentVariables.Set(SpecialVariables.ClusterUrl, ServerUrl);

                    deploymentVariables.Set(SpecialVariables.SkipTlsVerification, "true");
                    deploymentVariables.Set(SpecialVariables.Namespace, "calamari-testing");
                    deploymentVariables.Set(Deployment.SpecialVariables.Account.AccountType, "Token");
                    deploymentVariables.Set(Deployment.SpecialVariables.Account.Token, ClusterToken);

                    var output = ExecuteScript(wrapper, temp.FilePath, deploymentVariables);
                    output.AssertSuccess();
                }
        }
Exemple #29
0
        void RunAdditionalPathsTest(
            bool fileExistsInPath,
            bool fileExistsInAdditionalPath,
            Action <IFileFormatVariableReplacer> replacerAssertions = null,
            Action <InMemoryLog> logAssertions = null)
        {
            var fileSystem = Substitute.For <ICalamariFileSystem>();

            fileSystem.FileExists(ConfigFileInCurrentPath).Returns(fileExistsInPath);
            fileSystem.FileExists(ConfigFileInAdditionalPath).Returns(fileExistsInAdditionalPath);
            fileSystem.EnumerateFilesWithGlob(CurrentPath, FileName)
            .Returns(fileExistsInPath ? new[] { ConfigFileInCurrentPath } : new string[0]);
            fileSystem.EnumerateFilesWithGlob(AdditionalPath, FileName)
            .Returns(fileExistsInAdditionalPath ? new[] { ConfigFileInAdditionalPath } : new string[0]);

            var replacer = Substitute.For <IFileFormatVariableReplacer>();

            replacer.FileFormatName.Returns(StructuredConfigVariablesFileFormats.Json);
            replacer.IsBestReplacerForFileName(Arg.Any <string>()).Returns(true);

            var log     = new InMemoryLog();
            var service = new StructuredConfigVariablesService(new []
            {
                replacer
            }, fileSystem, log);

            var variables = new CalamariVariables();

            variables.Set(ActionVariables.AdditionalPaths, AdditionalPath);
            variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables);
            variables.Set(ActionVariables.StructuredConfigurationVariablesTargets, FileName);
            variables.Set(PackageVariables.CustomInstallationDirectory, CurrentPath);

            var deployment = new RunningDeployment(CurrentPath, variables)
            {
                CurrentDirectoryProvider = DeploymentWorkingDirectory.CustomDirectory
            };

            service.ReplaceVariables(deployment);

            replacerAssertions?.Invoke(replacer);
            logAssertions?.Invoke(log);
        }
        public void ShouldRunBashInsteadOfPowerShell()
        {
            var variablesFile = Path.GetTempFileName();

            var variables = new CalamariVariables();

            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");
            }
        }