Beispiel #1
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));
            }
        }
Beispiel #2
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

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

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

            variables.Set(SpecialVariables.Action.Azure.CloudServicePackagePath, packageFile);
            variables.Set(KnownVariables.OriginalPackageDirectoryPath, !string.IsNullOrWhiteSpace(destinationDirectory) ? destinationDirectory : Path.GetDirectoryName(packageFile));

            var fileSystem = new WindowsPhysicalFileSystem();

            var conventions = new List <IConvention>
            {
                new EnsureCloudServicePackageIsCtpFormatConvention(fileSystem),
                new ExtractAzureCloudServicePackageConvention(log, fileSystem),
            };

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

            conventionRunner.RunConventions();

            return(0);
        }
        public static void SetOutputVariable(this IVariables variables, string name, string?value)
        {
            variables.Set(name, value);

            // And set the output-variables.
            // Assuming we are running in a step named 'DeployWeb' and are setting a variable named 'Foo'
            // then we will set Octopus.Action[DeployWeb].Output.Foo
            var actionName = variables.Get(ActionVariables.Name);

            if (string.IsNullOrWhiteSpace(actionName))
            {
                return;
            }

            var actionScopedVariable = ActionVariables.GetOutputVariableName(actionName, name);

            variables.Set(actionScopedVariable, value);

            // And if we are on a machine named 'Web01'
            // Then we will set Octopus.Action[DeployWeb].Output[Web01].Foo
            var machineName = variables.Get(MachineVariables.Name);

            if (string.IsNullOrWhiteSpace(machineName))
            {
                return;
            }

            var machineIndexedVariableName = ActionVariables.GetMachineIndexedOutputVariableName(actionName, machineName, name);

            variables.Set(machineIndexedVariableName, value);
        }
Beispiel #4
0
        void WriteVariableScriptToFile()
        {
            if (!TryGetScriptFromVariables(out var scriptBody, out var relativeScriptFile, out var scriptSyntax) &&
                !WasProvided(variables.Get(ScriptVariables.ScriptFileName)))
            {
                throw new CommandException($"Could not determine script to run.  Please provide either a `{ScriptVariables.ScriptBody}` variable, " +
                                           $"or a `{ScriptVariables.ScriptFileName}` variable.");
            }

            if (WasProvided(scriptBody))
            {
                var scriptFile = Path.GetFullPath(relativeScriptFile);

                //Set the name of the script we are about to create to the variables collection for replacement later on
                variables.Set(ScriptVariables.ScriptFileName, relativeScriptFile);

                // If the script body was supplied via a variable, then we write it out to a file.
                // This will be deleted with the working directory.
                // Bash files need SheBang as first few characters. This does not play well with BOM characters
                var scriptBytes = scriptSyntax == ScriptSyntax.Bash
                    ? scriptBody.EncodeInUtf8NoBom()
                    : scriptBody.EncodeInUtf8Bom();
                File.WriteAllBytes(scriptFile, scriptBytes);
            }
        }
Beispiel #5
0
        public CommandResult ExecuteScript(Script script,
                                           ScriptSyntax scriptSyntax,
                                           ICommandLineRunner commandLineRunner,
                                           Dictionary <string, string> 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}.{CertificateVariables.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, commandLineRunner, environmentVars));
                }
        }
Beispiel #6
0
        public void CanTransformConfigInJar()
        {
            const string configFile = "config.properties";

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

            DeployPackage(TestEnvironment.GetTestPath("Java", "Fixtures", "Deployment", "Packages", "HelloWorld.0.0.1.jar"));
            Assert.AreEqual(0, returnCode);
            log.StandardOut.Should().Contain($"Performing variable substitution on '{Path.Combine(Environment.CurrentDirectory, "staging", configFile)}'");
        }
Beispiel #7
0
        public void ShouldSkipIfInstalled()
        {
            variables.Set(SpecialVariables.Package.SkipIfAlreadyInstalled, true.ToString());
            previous = new JournalEntry("123", "tenant", "env", "proj", "rp01", DateTime.Now, "C:\\App", "C:\\MyApp", true,
                                        new List <DeployedPackage> {
                new DeployedPackage("pkg", "0.0.9", "C:\\PackageOld.nupkg")
            });

            RunConvention();

            Assert.That(variables.Get(KnownVariables.Action.SkipJournal), Is.EqualTo("true"));
        }
        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));
                    }
                }
        }
 public void Setup()
 {
     variables = new CalamariVariables();
     variables.Set(KnownVariables.Calamari.EnablePackageRetention, bool.TrueString);
     variables.Set(TentacleVariables.Agent.TentacleHome, "SomeDirectory");
     journalRepository = new InMemoryJournalRepository();
     packageJournal    = new PackageJournal(
         journalRepository,
         Substitute.For <ILog>(),
         Substitute.For <ICalamariFileSystem>(),
         Substitute.For <IRetentionAlgorithm>(),
         Substitute.For <ISemaphoreFactory>()
         );
 }
        private string CreateAzureCertificate(string workingDirectory, IVariables variables)
        {
            var certificateFilePath = Path.Combine(workingDirectory, CertificateFileName);
            var certificatePassword = GenerateCertificatePassword();
            var azureCertificate    = certificateStore.GetOrAdd(
                variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint),
                Convert.FromBase64String(variables.Get(SpecialVariables.Action.Azure.CertificateBytes)),
                StoreName.My);

            variables.Set("OctopusAzureCertificateFileName", certificateFilePath);
            variables.Set("OctopusAzureCertificatePassword", certificatePassword);

            fileSystem.WriteAllBytes(certificateFilePath, azureCertificate.Export(X509ContentType.Pfx, certificatePassword));
            return(certificateFilePath);
        }
Beispiel #11
0
        public void SetUp()
        {
            fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
            configurationTransformer = Substitute.For <IConfigurationTransformer>();
            transformFileLocator     = new TransformFileLocator(fileSystem);

            var deployDirectory = BuildConfigPath(null);

            variables = new CalamariVariables();
            variables.Set(SpecialVariables.Package.EnabledFeatures, SpecialVariables.Features.ConfigurationTransforms);
            variables.Set(KnownVariables.OriginalPackageDirectoryPath, deployDirectory);

            deployment = new RunningDeployment(deployDirectory, variables);
            logs       = new InMemoryLog();
        }
Beispiel #12
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            variables.Set(KnownVariables.OriginalPackageDirectoryPath, Environment.CurrentDirectory);
            var fileSystem       = new WindowsPhysicalFileSystem();
            var filesInPackage   = !string.IsNullOrWhiteSpace(pathToPackage);
            var templateResolver = new TemplateResolver(fileSystem);
            var templateService  = new TemplateService(fileSystem, templateResolver, new TemplateReplacement(templateResolver));

            var conventions = new List <IConvention>
            {
                new DelegateInstallConvention(d => extractPackage.ExtractToStagingDirectory(pathToPackage)),
                new ConfiguredScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner),
                new PackagedScriptConvention(log, DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner),
                new PackagedScriptConvention(log, DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner),
                new DeployAzureResourceGroupConvention(templateFile, templateParameterFile, filesInPackage, templateService, new ResourceGroupTemplateNormalizer()),
                new PackagedScriptConvention(log, DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner),
            };

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

            conventionRunner.RunConventions();
            return(0);
        }
Beispiel #13
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));
            }
        }
Beispiel #14
0
 public void SetUp()
 {
     variables = new CalamariVariables();
     variables.Set(KnownVariables.OriginalPackageDirectoryPath, stagingDirectory);
     fileSystem = Substitute.For <ICalamariFileSystem>();
     deployment = new RunningDeployment(packageFilePath, variables);
 }
Beispiel #15
0
        void Extract(PathToPackage pathToPackage, string targetPath, IPackageExtractor customPackageExtractor)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(pathToPackage))
                {
                    log.Verbose("No package path defined. Skipping package extraction.");
                    return;
                }

                log.Verbose("Extracting package to: " + targetPath);

                var extractorToUse = customPackageExtractor ?? combinedPackageExtractor;
                var filesExtracted = extractorToUse.Extract(pathToPackage, targetPath);

                log.Verbose("Extracted " + filesExtracted + " files");

                variables.Set(KnownVariables.OriginalPackageDirectoryPath, targetPath);
                log.SetOutputVariable(PackageVariables.Output.InstallationDirectoryPath, targetPath, variables);
                log.SetOutputVariable(PackageVariables.Output.DeprecatedInstallationDirectoryPath, targetPath, variables);
                log.SetOutputVariable(PackageVariables.Output.ExtractedFileCount, filesExtracted.ToString(), variables);
            }
            catch (UnauthorizedAccessException)
            {
                LogAccessDenied();
                throw;
            }
            catch (Exception ex) when(ex.Message.ContainsIgnoreCase("Access is denied"))
            {
                LogAccessDenied();
                throw;
            }
        }
Beispiel #16
0
        public void ShouldUpdatePath()
        {
            const string websiteName = "AcmeOnline";

            variables.Set(SpecialVariables.Package.UpdateIisWebsite, true.ToString());
            variables.Set(SpecialVariables.Package.UpdateIisWebsiteName, websiteName);
            fileSystem.FileExists(Path.Combine(stagingDirectory, "Web.config")).Returns(true);
            iis.OverwriteHomeDirectory(websiteName, stagingDirectory, false).Returns(true);

            CreateConvention().Install(deployment);

            iis.Received().OverwriteHomeDirectory(websiteName, stagingDirectory, false);
        }
Beispiel #17
0
 public static IVariables CopyFromDictionary(this IVariables v, IDictionary dict, bool mustOverride = true)
 {
     foreach (DictionaryEntry kvp in Environment.GetEnvironmentVariables())
     {
         v.Set(kvp.Key.ToString(), kvp.Value);
     }
     return(v);
 }
        public void ShouldRunScriptAtAppropriateStage()
        {
            const string stage      = DeploymentStages.PostDeploy;
            const string scriptBody = "lorem ipsum blah blah blah";
            var          scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.PowerShell);
            var          scriptPath = Path.Combine(stagingDirectory, scriptName);
            var          script     = new Script(scriptPath);

            variables.Set(scriptName, scriptBody);

            var convention = CreateConvention(stage);

            scriptEngine.Execute(Arg.Any <Script>(), variables, commandLineRunner).Returns(new CommandResult("", 0));
            convention.Install(deployment);

            fileSystem.Received().WriteAllBytes(scriptPath, Arg.Any <byte[]>());
            scriptEngine.Received().Execute(Arg.Is <Script>(s => s.File == scriptPath), variables, commandLineRunner);
        }
Beispiel #19
0
 private Action <RunningChangeSet> ApplyVariables(IVariables variables)
 {
     return(result =>
     {
         SetOutputVariable(variables, "ChangesetId", result.ChangeSet.Value);
         SetOutputVariable(variables, "StackId", result.Stack.Value);
         variables.Set(AwsSpecialVariables.CloudFormation.Changesets.Arn, result.ChangeSet.Value);
     });
 }
Beispiel #20
0
        public void ShouldCreateScriptFileIfNotExists()
        {
            const string deployStage = "BeforePostDeploy";
            const string feature     = "doTheThing";
            var          scriptPath  = Path.Combine(stagingDirectory, FeatureConvention.GetScriptName(feature, deployStage, "ps1"));

            variables.Set(SpecialVariables.Package.EnabledFeatures, feature);

            Arrange(new List <string> {
                feature
            }, deployStage);
            fileSystem.FileExists(scriptPath).Returns(false);

            var convention = CreateConvention(deployStage);

            scriptEngine.Execute(Arg.Is <Script>(s => s.File == scriptPath), variables, commandLineRunner).Returns(new CommandResult("", 0));
            convention.Install(deployment);

            fileSystem.Received().OverwriteFile(scriptPath, scriptContents);
        }
        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));
                    }
                }
        }
        public void SetUp()
        {
            log = Substitute.For <ILog>();
            log.When(x => x.SetOutputVariable(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <IVariables>()))
            .Do(x => outputVars.Add(x.ArgAt <string>(0), x.ArgAt <string>(1)));

            calamariFileSystem = Substitute.For <ICalamariFileSystem>();
            commandLineRunner  = Substitute.For <ICommandLineRunner>();
            variables          = new CalamariVariables();
            variables.Set(TerraformSpecialVariables.Action.Terraform.PlanJsonOutput, "True");
            runningDeployment = Substitute.For <RunningDeployment>(variables);
        }
        public void DeployTemplate(string resourceName, string templateFilePath, IVariables variables)
        {
            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);
            variables.Save(variablesFile);

            using (var templateFile = new TemporaryFile(templateFilePath))
                using (new TemporaryFile(variablesFile))
                {
                    var log        = new InMemoryLog();
                    var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
                    var command    = new DeployCloudFormationCommand(
                        log,
                        variables,
                        fileSystem,
                        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[]
                    {
                        "--template", $"{templateFile.FilePath}",
                        "--variables", $"{variablesFile}",
                        "--stackName", resourceName,
                        "--waitForCompletion", "true"
                    });

                    result.Should().Be(0);
                }
        }
Beispiel #24
0
        void ParseServiceMessage(ServiceMessage message)
        {
            switch (message.Name)
            {
            case ServiceMessageNames.SetVariable.Name:
                var variableName  = message.GetValue(ServiceMessageNames.SetVariable.NameAttribute);
                var variableValue = message.GetValue(ServiceMessageNames.SetVariable.ValueAttribute);

                if (!string.IsNullOrWhiteSpace(variableName))
                {
                    outputVariables.Set(variableName, variableValue);
                }
                break;

            case ServiceMessageNames.CalamariFoundPackage.Name:
                CalamariFoundPackage = true;
                break;

            case ServiceMessageNames.FoundPackage.Name:
                var foundPackageId            = message.GetValue(ServiceMessageNames.FoundPackage.IdAttribute);
                var foundPackageVersion       = message.GetValue(ServiceMessageNames.FoundPackage.VersionAttribute);
                var foundPackageVersionFormat = message.GetValue(ServiceMessageNames.FoundPackage.VersionFormat);
                var foundPackageHash          = message.GetValue(ServiceMessageNames.FoundPackage.HashAttribute);
                var foundPackageRemotePath    = message.GetValue(ServiceMessageNames.FoundPackage.RemotePathAttribute);
                var fileExtension             = message.GetValue(ServiceMessageNames.FoundPackage.FileExtensionAttribute);
                if (foundPackageId != null && foundPackageVersion != null)
                {
                    FoundPackage = new FoundPackage(foundPackageId,
                                                    foundPackageVersion,
                                                    foundPackageVersionFormat,
                                                    foundPackageRemotePath,
                                                    foundPackageHash,
                                                    fileExtension);
                }
                break;

            case ServiceMessageNames.PackageDeltaVerification.Name:
                var pdvHash       = message.GetValue(ServiceMessageNames.PackageDeltaVerification.HashAttribute);
                var pdvSize       = message.GetValue(ServiceMessageNames.PackageDeltaVerification.SizeAttribute);
                var pdvRemotePath =
                    message.GetValue(ServiceMessageNames.PackageDeltaVerification.RemotePathAttribute);
                DeltaError = message.GetValue(ServiceMessageNames.PackageDeltaVerification.Error);
                if (pdvRemotePath != null && pdvHash != null)
                {
                    DeltaVerification = new DeltaPackage(pdvRemotePath, pdvHash, long.Parse(pdvSize));
                }

                break;
            }
        }
Beispiel #25
0
        public virtual void SetUp()
        {
            fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
            log        = new InMemoryLog();

            // Ensure staging directory exists and is empty
            applicationDirectory = Path.Combine(Path.GetTempPath(), "CalamariTestStaging");
            fileSystem.EnsureDirectoryExists(applicationDirectory);
            fileSystem.PurgeDirectory(applicationDirectory, FailureOptions.ThrowOnFailure);

            Environment.SetEnvironmentVariable("TentacleJournal", Path.Combine(applicationDirectory, "DeploymentJournal.xml"));

            variables = new VariablesFactory(fileSystem).Create(new CommonOptions("test"));
            variables.Set(TentacleVariables.Agent.ApplicationDirectoryPath, applicationDirectory);
        }
        public void SetUp()
        {
            fileSystem        = Substitute.For <ICalamariFileSystem>();
            scriptEngine      = Substitute.For <IScriptEngine>();
            commandLineRunner = Substitute.For <ICommandLineRunner>();

            scriptEngine.GetSupportedTypes().Returns(new[] { ScriptSyntax.PowerShell });

            variables = new CalamariVariables();
            variables.Set(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.CustomScripts);

            deployment = new RunningDeployment("C:\\packages", variables)
            {
                StagingDirectory = stagingDirectory
            };
        }
Beispiel #27
0
        public void SetUp()
        {
            fileSystem        = Substitute.For <ICalamariFileSystem>();
            embeddedResources = Substitute.For <ICalamariEmbeddedResources>();
            scriptEngine      = Substitute.For <IScriptEngine>();
            commandLineRunner = Substitute.For <ICommandLineRunner>();

            scriptEngine.GetSupportedTypes().Returns(new[] { ScriptSyntax.PowerShell });

            variables = new CalamariVariables();
            variables.Set(SpecialVariables.Package.EnabledFeatures, "Octopus.Features.blah");

            deployment = new RunningDeployment("C:\\packages", variables)
            {
                StagingDirectory = stagingDirectory
            };
        }
Beispiel #28
0
        internal static void PreviousSuccessful(IVariables variables, IDeploymentJournal journal, string policySet)
        {
            var previous = journal.GetLatestSuccessfulInstallation(policySet);

            if (previous == null)
            {
                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.OriginalInstalledPath, "");
                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.CustomInstallationDirectory, "");
                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageFilePath, "");
                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageVersion, "");
            }
            else
            {
                var previousPackage = previous.Packages.FirstOrDefault();

                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.OriginalInstalledPath, previous.ExtractedTo);
                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.CustomInstallationDirectory, previous.CustomInstallationDirectory);
                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageFilePath, previousPackage?.DeployedFrom ?? "");
                variables.Set(TentacleVariables.PreviousSuccessfulInstallation.PackageVersion, previousPackage?.PackageVersion ?? "");
            }
        }
Beispiel #29
0
        protected override int ExecuteInternal(NodeInstructions instructions)
        {
            using (var variableFile = new TemporaryFile(Path.GetTempFileName()))
            {
                var jsonInputs = variables.GetRaw(instructions.InputsVariable) ?? string.Empty;
                variables.Set(instructions.InputsVariable, InputSubstitution.SubstituteAndEscapeAllVariablesInJson(jsonInputs, variables, log));
                var variablesAsJson = variables.CloneAndEvaluate().SaveAsString();
                File.WriteAllBytes(variableFile.FilePath, new AesEncryption(options.InputVariables.SensitiveVariablesPassword).Encrypt(variablesAsJson));
                var pathToNode            = variables.Get(instructions.NodePathVariable);
                var nodeExecutablePath    = BuildNodePath(pathToNode);
                var parameters            = BuildParams(instructions, variableFile.FilePath);
                var runningDeployment     = new RunningDeployment(variables);
                var commandLineInvocation = new CommandLineInvocation(nodeExecutablePath, parameters)
                {
                    WorkingDirectory = runningDeployment.CurrentDirectory,
                    OutputToLog      = true,
                    EnvironmentVars  = ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables().ToDictionary(e => e.Key, e => e.Value)
                };

                var commandResult = commandLineRunner.Execute(commandLineInvocation);
                return(commandResult.ExitCode);
            }
        }
Beispiel #30
0
        public void ShouldApplyReleaseTransformIfAutomaticallyRunConfigurationTransformationFilesFlagIsSet()
        {
            variables.Set(SpecialVariables.Package.AutomaticallyRunConfigurationTransformationFiles, true.ToString());

            CreateConvention().Install(deployment);

            AssertTransformRun("bar.config", "bar.Release.config");
        }