Example #1
0
        private static SitePublishProfile GetPublishProfile(VariableDictionary variables)
        {
            var subscriptionId = variables.Get(SpecialVariables.Action.Azure.SubscriptionId);
            var siteName       = variables.Get(SpecialVariables.Action.Azure.WebAppName);

            var accountType             = variables.Get(SpecialVariables.Account.AccountType);
            var activeDirectoryEndpoint = variables.Get(SpecialVariables.Action.Azure.ActiveDirectoryEndPoint, DefaultVariables.ActiveDirectoryEndpoint);

            switch (accountType)
            {
            case AzureAccountTypes.ServicePrincipalAccountType:
                var resourceManagementEndpoint = variables.Get(SpecialVariables.Action.Azure.ResourceManagementEndPoint, DefaultVariables.ResourceManagementEndpoint);
                return(ResourceManagerPublishProfileProvider.GetPublishProperties(subscriptionId,
                                                                                  variables.Get(SpecialVariables.Action.Azure.ResourceGroupName, string.Empty),
                                                                                  siteName,
                                                                                  variables.Get(SpecialVariables.Action.Azure.TenantId),
                                                                                  variables.Get(SpecialVariables.Action.Azure.ClientId),
                                                                                  variables.Get(SpecialVariables.Action.Azure.Password),
                                                                                  resourceManagementEndpoint,
                                                                                  activeDirectoryEndpoint));

            case AzureAccountTypes.ManagementCertificateAccountType:
                var serviceManagementEndpoint = variables.Get(SpecialVariables.Action.Azure.ServiceManagementEndPoint, DefaultVariables.ServiceManagementEndpoint);
                return(ServiceManagementPublishProfileProvider.GetPublishProperties(subscriptionId,
                                                                                    Convert.FromBase64String(variables.Get(SpecialVariables.Action.Azure.CertificateBytes)),
                                                                                    siteName,
                                                                                    serviceManagementEndpoint));

            default:
                throw new CommandException(
                          "Account type must be either Azure Management Certificate or Azure Service Principal");
            }
        }
Example #2
0
        static void UpdateConfigurationSettings(XContainer configurationFile, VariableDictionary variables)
        {
            Log.Verbose("Updating configuration settings...");
            var foundSettings = false;

            WithConfigurationSettings(configurationFile, (roleName, settingName, settingValueAttribute) =>
            {
                var setting = variables.Get(roleName + "/" + settingName) ??
                              variables.Get(roleName + "\\" + settingName) ??
                              variables.Get(settingName) ??
                              (variables.GetNames().Contains(settingName) ? "" : null);

                if (setting != null)
                {
                    foundSettings = true;
                    Log.Info("Updating setting for role {0}: {1} = {2}", roleName, settingName, setting);
                    settingValueAttribute.Value = setting;
                }
            });

            if (!foundSettings)
            {
                Log.Info("No settings that match provided variables were found.");
            }
        }
        static void UpdateConfigurationSettings(XContainer configurationFile, VariableDictionary variables)
        {
            Log.Verbose("Updating configuration settings...");
            var foundSettings = false;

            WithConfigurationSettings(configurationFile, (roleName, settingName, settingValueAttribute) =>
            {
                var setting = variables.Get(roleName + "/" + settingName) ??
                            variables.Get(roleName + "\\" + settingName) ??
                            variables.Get(settingName) ??
                            (variables.GetNames().Contains(settingName) ? "" : null);
                
                if (setting != null)
                {
                    foundSettings = true;
                    Log.Info("Updating setting for role {0}: {1} = {2}", roleName, settingName, setting);
                    settingValueAttribute.Value = setting;
                }
            });

            if (!foundSettings)
            {
                Log.Info("No settings that match provided variables were found.");
            }
        }
        public static void SetOutputVariable(this VariableDictionary 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(SpecialVariables.Action.Name);

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

            var actionScopedVariable = SpecialVariables.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(SpecialVariables.Machine.Name);

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

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

            variables.Set(machineIndexedVariableName, value);
        }
        public X509Certificate2 GetOrAdd(VariableDictionary variables, string certificateVariable, StoreName storeName, StoreLocation storeLocation = StoreLocation.CurrentUser)
        {
            var pfxBytes   = Convert.FromBase64String(variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Pfx}"));
            var thumbprint = variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Thumbprint}");
            var password   = variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Password}");

            return(GetOrAdd(thumbprint, pfxBytes, password, new X509Store(storeName, storeLocation)));
        }
        void UpdateConfigurationWithCurrentInstanceCount(XContainer localConfigurationFile, string configurationFileName, VariableDictionary variables)
        {
            if (!variables.GetFlag(SpecialVariables.Action.Azure.UseCurrentInstanceCount))
            {
                return;
            }

            var serviceName = variables.Get(SpecialVariables.Action.Azure.CloudServiceName);
            var slot        = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), variables.Get(SpecialVariables.Action.Azure.Slot));

            var remoteConfigurationFile = configurationRetriever.GetConfiguration(
                credentialsFactory.GetCredentials(variables.Get(SpecialVariables.Action.Azure.SubscriptionId),
                                                  variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint),
                                                  variables.Get(SpecialVariables.Action.Azure.CertificateBytes)),
                serviceName,
                slot);

            if (remoteConfigurationFile == null)
            {
                Log.Info("There is no current deployment of service '{0}' in slot '{1}', so existing instance counts will not be imported.", serviceName, slot);
                return;
            }

            var rolesByCount = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            Log.Verbose("Local instance counts (from " + Path.GetFileName(configurationFileName) + "): ");
            WithInstanceCounts(localConfigurationFile, (roleName, attribute) =>
            {
                Log.Verbose(" - " + roleName + " = " + attribute.Value);

                string value;
                if (rolesByCount.TryGetValue(roleName, out value))
                {
                    attribute.SetValue(value);
                }
            });

            Log.Verbose("Remote instance counts: ");
            WithInstanceCounts(remoteConfigurationFile, (roleName, attribute) =>
            {
                rolesByCount[roleName] = attribute.Value;
                Log.Verbose(" - " + roleName + " = " + attribute.Value);
            });

            Log.Verbose("Replacing local instance count settings with remote settings: ");
            WithInstanceCounts(localConfigurationFile, (roleName, attribute) =>
            {
                string value;
                if (!rolesByCount.TryGetValue(roleName, out value))
                {
                    return;
                }

                attribute.SetValue(value);
                Log.Verbose(" - " + roleName + " = " + attribute.Value);
            });
        }
Example #7
0
        public void ShouldSkipIfInstalled()
        {
            variables.Set(SpecialVariables.Package.SkipIfAlreadyInstalled, true.ToString());
            previous = new JournalEntry("123", "env", "proj", "pkg", "0.0.9", "rp01", DateTime.Now, "C:\\PackageOld.nupkg", "C:\\App", "C:\\MyApp", true);

            RunConvention();

            Assert.That(variables.Get(SpecialVariables.Action.SkipJournal), Is.EqualTo("true"));
        }
        public SubscriptionCloudCredentials GetCredentials(VariableDictionary variables)
        {
            var subscriptionId        = variables.Get(SpecialVariables.Action.Azure.SubscriptionId);
            var certificateThumbprint = variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint);
            var certificateBytes      = Convert.FromBase64String(variables.Get(SpecialVariables.Action.Azure.CertificateBytes));

            var certificate = certificateStore.GetOrAdd(certificateThumbprint, certificateBytes);

            return(new CertificateCloudCredentials(subscriptionId, certificate));
        }
        void UpdateConfigurationWithCurrentInstanceCount(XContainer localConfigurationFile, string configurationFileName, VariableDictionary variables)
        {
            if (!variables.GetFlag(SpecialVariables.Action.Azure.UseCurrentInstanceCount))
                return;

            var serviceName = variables.Get(SpecialVariables.Action.Azure.CloudServiceName);
            var slot = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), variables.Get(SpecialVariables.Action.Azure.Slot));

            var remoteConfigurationFile = configurationRetriever.GetConfiguration(
                credentialsFactory.GetCredentials(variables.Get(SpecialVariables.Action.Azure.SubscriptionId),
                    variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint),
                    variables.Get(SpecialVariables.Action.Azure.CertificateBytes)),
                serviceName,
                slot);

            if (remoteConfigurationFile == null)
            {
                Log.Info("There is no current deployment of service '{0}' in slot '{1}', so existing instance counts will not be imported.", serviceName, slot);
                return;
            }

            var rolesByCount = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            Log.Verbose("Local instance counts (from " + Path.GetFileName(configurationFileName) + "): ");
            WithInstanceCounts(localConfigurationFile, (roleName, attribute) =>
            {
                Log.Verbose(" - " + roleName + " = " + attribute.Value);

                string value;
                if (rolesByCount.TryGetValue(roleName, out value))
                {
                    attribute.SetValue(value);
                }
            });

            Log.Verbose("Remote instance counts: ");
            WithInstanceCounts(remoteConfigurationFile, (roleName, attribute) =>
            {
                rolesByCount[roleName] = attribute.Value;
                Log.Verbose(" - " + roleName + " = " + attribute.Value);
            });

            Log.Verbose("Replacing local instance count settings with remote settings: ");
            WithInstanceCounts(localConfigurationFile, (roleName, attribute) =>
            {
                string value;
                if (!rolesByCount.TryGetValue(roleName, out value)) 
                    return;

                attribute.SetValue(value);
                Log.Verbose(" - " + roleName + " = " + attribute.Value);
            });
        }
Example #10
0
        private string CreateAzureCertificate(string workingDirectory, VariableDictionary 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);
        }
        private string CreateAzureCertificate(string workingDirectory, VariableDictionary variables)
        {
            var certificateFilePath = Path.Combine(workingDirectory, CertificateFileName);
            var certificatePassword = GenerateCertificatePassword();
            var azureCertificate = certificateStore.GetOrAdd(
                variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint),
                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;
        }
 static void SetOutputVariable(string name, string value, VariableDictionary variables)
 {
     if (variables.Get(name) != value)
     {
         Log.SetOutputVariable(name, value, variables);
     }
 }
Example #13
0
        static IEnumerable <string> ReplaceAppSettingOrConnectionString(XNode document, string xpath, string keyAttributeName, string keyAttributeValue, string valueAttributeName, VariableDictionary variables)
        {
            var changes  = new List <string>();
            var settings = (
                from element in document.XPathSelectElements(xpath)
                let keyAttribute = element.Attribute(keyAttributeName)
                                   where keyAttribute != null
                                   where string.Equals(keyAttribute.Value, keyAttributeValue, StringComparison.OrdinalIgnoreCase)
                                   select element).ToList();

            if (settings.Count == 0)
            {
                return(changes);
            }

            var value = variables.Get(keyAttributeValue) ?? string.Empty;

            foreach (var setting in settings)
            {
                changes.Add(string.Format("Setting '{0}' = '{1}'", keyAttributeValue, value));

                var valueAttribute = setting.Attribute(valueAttributeName);
                if (valueAttribute == null)
                {
                    setting.Add(new XAttribute(valueAttributeName, value));
                }
                else
                {
                    valueAttribute.SetValue(value);
                }
            }

            return(changes);
        }
        static IEnumerable<string> ReplaceAppSettingOrConnectionString(XNode document, string xpath, string keyAttributeName, string keyAttributeValue, string valueAttributeName, VariableDictionary variables)
        {
            var changes = new List<string>();
            var settings = (
                from element in document.XPathSelectElements(xpath)
                let keyAttribute = element.Attribute(keyAttributeName)
                where keyAttribute != null
                where string.Equals(keyAttribute.Value, keyAttributeValue, StringComparison.InvariantCultureIgnoreCase)
                select element).ToList();

            if (settings.Count == 0)
                return changes;

            var value = variables.Get(keyAttributeValue) ?? string.Empty;

            foreach (var setting in settings)
            {
                changes.Add(string.Format("Setting '{0}' = '{1}'", keyAttributeValue, value));

                var valueAttribute = setting.Attribute(valueAttributeName);
                if (valueAttribute == null)
                {
                    setting.Add(new XAttribute(valueAttributeName, value));
                }
                else
                {
                    valueAttribute.SetValue(value);
                }
            }

            return changes;
        }
        static IEnumerable <string> ReplaceStonglyTypeApplicationSetting(XNode document, string xpath, string keyAttributeName, string keyAttributeValue, VariableDictionary variables)
        {
            var changes = new List <string>();

            var settings = (
                from element in document.XPathSelectElements(xpath)
                let keyAttribute = element.Attribute(keyAttributeName)
                                   where keyAttribute != null
                                   where string.Equals(keyAttribute.Value, keyAttributeValue, StringComparison.InvariantCultureIgnoreCase)
                                   select element).ToList();

            if (settings.Count == 0)
            {
                return(changes);
            }

            var value = variables.Get(keyAttributeValue) ?? string.Empty;

            foreach (var setting in settings)
            {
                changes.Add(string.Format("Setting '{0}' = '{1}'", keyAttributeValue, value));

                var valueElement = setting.Elements().FirstOrDefault(e => e.Name.LocalName == "value");
                if (valueElement == null)
                {
                    setting.Add(new XElement("value", value));
                }
                else
                {
                    valueElement.SetValue(value);
                }
            }

            return(changes);
        }
Example #16
0
        string GetAccountId(IDictionary <string, string> messageProperties,
                            VariableDictionary variables, Func <string, string> accountIdResolver, ITaskLog taskLog)
        {
            messageProperties.TryGetValue(AzureWebAppServiceMessageNames.AccountIdOrNameAttribute, out var accountIdOrName);
            if (!string.IsNullOrWhiteSpace(accountIdOrName))
            {
                var resolvedAccountId = accountIdResolver(accountIdOrName);

                if (!string.IsNullOrWhiteSpace(resolvedAccountId))
                {
                    return(resolvedAccountId);
                }
            }

            accountIdOrName = variables.Get(SpecialVariables.Action.Azure.AccountId);
            if (!string.IsNullOrWhiteSpace(accountIdOrName))
            {
                var resolvedAccountId = accountIdResolver(accountIdOrName);

                if (!string.IsNullOrWhiteSpace(resolvedAccountId))
                {
                    return(resolvedAccountId);
                }
            }

            var message = $"Account with Id / Name, {accountIdOrName}, not found.";

            taskLog.Error(message);
            throw new Exception(message);
        }
 void SetOutputVariable(string name, string value, VariableDictionary variables)
 {
     if (variables.Get(name) != value)
     {
         Log.SetOutputVariable(name, value, variables);
     }
 }
Example #18
0
        public void Update(VariableDictionary variables)
        {
            bool VariableNameIsNotASystemVariable(string v)
            {
                if (v.StartsWith("Octopus", StringComparison.OrdinalIgnoreCase))
                {
                    // Only include variables starting with 'Octopus'
                    // if it also has a colon (:)
                    if (v.StartsWith("Octopus:", StringComparison.OrdinalIgnoreCase))
                    {
                        return(map.ContainsKey(v));
                    }
                    else
                    {
                        return(false);
                    }
                }
                return(map.ContainsKey(v));
            }

            foreach (var name in variables.GetNames().Where(VariableNameIsNotASystemVariable))
            {
                try
                {
                    map[name](variables.Get(name));
                }
                catch (Exception e)
                {
                    Log.WarnFormat("Unable to set value for {0}. The following error occurred: {1}", name, e.Message);
                }
            }
        }
        private static string BuildPath(string site, VariableDictionary variables)
        {
            var relativePath = (variables.Get(SpecialVariables.Action.Azure.PhysicalPath) ?? "").TrimStart('\\');

            return relativePath != ""
                ? site + "\\" + relativePath
                : site;
        }
Example #20
0
        public void Required()
        {
            var variables = new VariableDictionary();

            variables.Set("FirstName", "Paul");
            variables.Get("FirstName").Should().Be("Paul");
            Assert.Throws <ArgumentOutOfRangeException>(() => variables.Require("LastName"));
        }
        private static string BuildPath(AzureTargetSite site, VariableDictionary variables)
        {
            var relativePath = (variables.Get(SpecialVariables.Action.Azure.PhysicalPath) ?? "").TrimStart('\\');

            return(relativePath != ""
                ? site.Site + "\\" + relativePath
                : site.Site);
        }
Example #22
0
        public ResolvedTemplatePath Resolve(string relativeFilePath, bool inPackage, VariableDictionary variables)
        {
            var result = MaybeResolve(relativeFilePath, inPackage, variables);

            if (result.Some())
            {
                return(result.Value);
            }

            var packageId      = variables.Get("Octopus.Action.Package.PackageId");
            var packageVersion = variables.Get("Octopus.Action.Package.PackageVersion");
            var packageMessage = inPackage ?
                                 $" in the package {packageId} {packageVersion}"
                : string.Empty;

            throw new CommandException($"Could not find '{relativeFilePath}'{packageMessage}");
        }
Example #23
0
        static string AddCertificateToStore(VariableDictionary variables, string certificateVariable, StoreLocation storeLocation, string storeName)
        {
            var pfxBytes = Convert.FromBase64String(variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Pfx}"));
            var password = variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Password}");
            var subject  = variables.Get($"{certificateVariable}.{SpecialVariables.Certificate.Properties.Subject}");

            Log.Info($"Adding certificate '{subject}' into Cert:\\{storeLocation}\\{storeName}");
            try
            {
                WindowsX509CertificateStore.ImportCertificateToStore(pfxBytes, password, storeLocation, storeName, true);
                return(storeName);
            }
            catch (Exception)
            {
                Log.Error("Exception while attempting to add certificate to store");
                throw;
            }
        }
        string GetInitialExtractionDirectory(VariableDictionary variables)
        {
            var root = variables.Get(SpecialVariables.Tentacle.Agent.ApplicationDirectoryPath)
                       ?? variables.Evaluate("#{env:SystemDrive}\\Applications");

            root = AppendEnvironmentNameIfProvided(variables, root);
            fileSystem.EnsureDirectoryExists(root);
            fileSystem.EnsureDiskHasEnoughFreeSpace(root);
            return(root);
        }
Example #25
0
        public void MissingVariable()
        {
            var dictionary = new VariableDictionary();

            dictionary.Set("Project.Namespace", "{Database.Name}.Core");

            var result = dictionary.Get("Project.Namespace");

            result.Should().Be(".Core");
        }
Example #26
0
        public Maybe <ResolvedTemplatePath> MaybeResolve(string relativeFilePath, bool inPackage, VariableDictionary variables)
        {
            var absolutePath = relativeFilePath.ToMaybe().Select(path => inPackage
                ? Path.Combine(variables.Get(SpecialVariables.OriginalPackageDirectoryPath), variables.Evaluate(path))
                : Path.Combine(Environment.CurrentDirectory, path));

            return(absolutePath.SelectValueOr(x =>
                                              !filesystem.FileExists(x) ? Maybe <ResolvedTemplatePath> .None : new ResolvedTemplatePath(x).AsSome(),
                                              Maybe <ResolvedTemplatePath> .None
                                              ));
        }
Example #27
0
        private string DetermineScriptFilePath(VariableDictionary variables)
        {
            var scriptFileName = variables.Get(SpecialVariables.Action.Script.ScriptFileName);

            if (!WasProvided(scriptFileName) && !WasProvided(scriptFileArg))
            {
                scriptFileName = "Script." + DetermineSyntax(variables).FileExtension();
            }

            return(Path.GetFullPath(WasProvided(scriptFileName) ? scriptFileName : scriptFileArg));
        }
Example #28
0
 static void WriteScriptModules(VariableDictionary variables, StringBuilder output)
 {
     foreach (var variableName in variables.GetNames().Where(SpecialVariables.IsLibraryScriptModule))
     {
         var name = "Library_" + new string(SpecialVariables.GetLibraryScriptModuleName(variableName).Where(char.IsLetterOrDigit).ToArray()) + "_" + DateTime.Now.Ticks;
         output.Append("New-Module -Name ").Append(name).Append(" -ScriptBlock {");
         output.AppendLine(variables.Get(variableName));
         output.AppendLine("} | Import-Module");
         output.AppendLine();
     }
 }
        string GetApplicationDirectoryPath (VariableDictionary variables)
        {
            const string windowsRoot = "env:SystemDrive";
            const string linuxRoot = "env:HOME";

            var root = variables.Get(SpecialVariables.Tentacle.Agent.ApplicationDirectoryPath);
            if (root != null)
                return root;

            root = variables.Get(windowsRoot);
            if (root == null)
            {
                root = variables.Get(linuxRoot);
                if (root == null)
                {
                    throw new Exception(string.Format("Unable to determine the ApplicationRootDirectory. Please provide the {0} variable", SpecialVariables.Tentacle.Agent.ApplicationDirectoryPath));
                }
            }
            return string.Format("{0}{1}Applications", root, Path.DirectorySeparatorChar);
        }
Example #30
0
        /// <summary>
        /// Execute java running the Octopus Deploy Java library
        /// </summary>
        public void Run(string mainClass, Dictionary <string, string> environmentVariables)
        {
            var javaLib = variables.Get(SpecialVariables.Action.Java.JavaLibraryEnvVar, "");
            var result  = commandLineRunner.Execute(new CommandLineInvocation(
                                                        JavaRuntime.CmdPath,
                                                        $"-Djdk.logger.finder.error=QUIET -cp calamari.jar {mainClass}",
                                                        Path.Combine(javaLib, "contentFiles", "any", "any"),
                                                        environmentVariables));

            result.VerifySuccess();
        }
Example #31
0
        public void FormatExceptionWithEscapedEndFormatBrace()
        {
            var dictionary = new VariableDictionary();

            dictionary.Set("Database.Name", "Tester");
            dictionary.Set("Project.Namespace", "{Database.Name}}.Core");

            Action action = () => dictionary.Get("Project.Namespace");

            action.Should().Throw <FormatException>();
        }
Example #32
0
        public void Evaluation()
        {
            var dictionary = new VariableDictionary();

            dictionary.Set("Database.Name", "Tester");
            dictionary.Set("Project.Namespace", "{Database.Name}.Core");

            var result = dictionary.Get("Project.Namespace");

            result.Should().Be("Tester.Core");
        }
        string AppendEnvironmentNameIfProvided(VariableDictionary variables, string root)
        {
            var environment = variables.Get(SpecialVariables.Environment.Name);
            if (!string.IsNullOrWhiteSpace(environment))
            {
                environment = fileSystem.RemoveInvalidFileNameChars(environment);
                root = Path.Combine(root, environment);
            }

            return root;
        }
Example #34
0
        string AppendEnvironmentNameIfProvided(VariableDictionary variables, string root)
        {
            var environment = variables.Get(SpecialVariables.Environment.Name);

            if (!string.IsNullOrWhiteSpace(environment))
            {
                environment = fileSystem.RemoveInvalidFileNameChars(environment);
                root        = Path.Combine(root, environment);
            }

            return(root);
        }
 static void WriteScriptModules(VariableDictionary variables, string parentDirectory, StringBuilder output)
 {
     foreach (var variableName in variables.GetNames().Where(SpecialVariables.IsLibraryScriptModule))
     {
         var name           = "Library_" + new string(SpecialVariables.GetLibraryScriptModuleName(variableName).Where(char.IsLetterOrDigit).ToArray()) + "_" + DateTime.Now.Ticks;
         var moduleFileName = $"{name}.psm1";
         var moduleFilePath = Path.Combine(parentDirectory, moduleFileName);
         CalamariFileSystem.OverwriteFile(moduleFilePath, variables.Get(variableName), Encoding.UTF8);
         output.AppendLine($"Import-ScriptModule '{SpecialVariables.GetLibraryScriptModuleName(variableName).EscapeSingleQuotedString()}' '{moduleFilePath.EscapeSingleQuotedString()}'");
         output.AppendLine();
     }
 }
Example #36
0
        public void InfiniteLoop()
        {
            var dictionary = new VariableDictionary();

            dictionary.Set("Database.Name", "{Project.Name}");
            dictionary.Set("Project.Name", "{Database.Name}");
            dictionary.Set("Project.Namespace", "{Database.Name}.Core");

            var result = dictionary.Get("Project.Namespace");

            result.Should().Be(".Core");
        }
Example #37
0
        public void ShouldSetVariables()
        {
            var variables = new VariableDictionary();

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

            output.AssertZero();
            output.AssertOutput("##octopus[setVariable name='VGVzdEE=' value='V29ybGQh']");
            Assert.AreEqual("World!", variables.Get("TestA"));
        }
        bool EnsureCertificateFileExists(string workingDirectory, VariableDictionary variables)
        {
            var certificateFilePath = Path.Combine(workingDirectory, certificateFileName);

            if (fileSystem.FileExists(certificateFileName))
                return true;

            var azureCertificate = certificateStore.GetOrAdd(
                variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint),
                variables.Get(SpecialVariables.Action.Azure.CertificateBytes),
                StoreName.My);

            var certificatePassword = GenerateCertificatePassword();

            fileSystem.WriteAllBytes(certificateFilePath, azureCertificate.Export(X509ContentType.Pfx, certificatePassword));

            Log.SetOutputVariable(SpecialVariables.Action.Azure.Output.CertificateFileName, certificateFilePath, variables);
            Log.SetOutputVariable(SpecialVariables.Action.Azure.Output.CertificatePassword, certificatePassword, variables);

            return false;
        }
Example #39
0
        public void ShouldSetVariables()
        {
            var variables = new VariableDictionary();

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

            output.AssertSuccess();
            output.AssertOutput("##octopus[setVariable name='VGVzdEE=' value='V29ybGQh']");
            Assert.AreEqual("World!", variables.Get("TestA"));
        }
        static string AppendTenantNameIfProvided(ICalamariFileSystem fileSystem, VariableDictionary variables, string root)
        {
            var tenant = variables.Get(SpecialVariables.Deployment.Tenant.Name);

            if (!string.IsNullOrWhiteSpace(tenant))
            {
                tenant = fileSystem.RemoveInvalidFileNameChars(tenant);
                root   = Path.Combine(root, tenant);
            }

            return(root);
        }
Example #41
0
        public CommandResult Execute(string scriptFile, VariableDictionary variables, ICommandLineRunner commandLineRunner)
        {
            var scriptType = Path.GetExtension(scriptFile).TrimStart('.').ToScriptType();
            var engine = GetSpecificScriptEngine(scriptType);

            // When running Powershell against an Azure target, we load the Azure Powershell modules,
            // and set the Azure subscription
            if (scriptType == ScriptType.Powershell &&
                variables.Get(SpecialVariables.Account.AccountType) == "AzureSubscription")
            {
                var azureContextScriptFile = azurePowershellContext.CreateAzureContextScript(scriptFile, variables);
                return engine.Execute(azureContextScriptFile, variables, commandLineRunner);
            }

            return engine.Execute(scriptFile, variables, commandLineRunner);
        }
        private Encoding GetEncoding(string sourceFile, VariableDictionary variables)
        {
            var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding);
            if (requestedEncoding == null)
            {
                return fileSystem.GetFileEncoding(sourceFile);
            }

            try
            {
                return Encoding.GetEncoding(requestedEncoding);
            }
            catch (ArgumentException)
            {
                return fileSystem.GetFileEncoding(sourceFile);
            }
        }
        public void Generate(string appSettingsFilePath, VariableDictionary variables)
        {
            var root = LoadJson(appSettingsFilePath);

            var names = variables.GetNames();
            names.Sort(StringComparer.OrdinalIgnoreCase);

            foreach (var name in names)
            {
                if (name.StartsWith("Octopus", StringComparison.OrdinalIgnoreCase))
                    continue;

                SetValueRecursive(root, name, name, variables.Get(name));
            }

            SaveJson(appSettingsFilePath, root);
        }
Example #44
0
 static IEnumerable<string> GetVariableSwitchConditions(VariableDictionary variables)
 {
     return variables.GetNames().Select(variable => string.Format("    \"{1}\"){0}    decode_servicemessagevalue \"{2}\"  ;;{0}", Environment.NewLine, EncodeValue(variable), EncodeValue(variables.Get(variable))));
 }
Example #45
0
 static void WriteVariableDictionary(VariableDictionary variables, StringBuilder output)
 {
     output.AppendLine("$OctopusParameters = New-Object 'System.Collections.Generic.Dictionary[String,String]' (,[System.StringComparer]::OrdinalIgnoreCase)");
     foreach (var variableName in variables.GetNames().Where(name => !SpecialVariables.IsLibraryScriptModule(name)))
     {
         output.Append("$OctopusParameters[").Append(EncodeValue(variableName)).Append("] = ").AppendLine(EncodeValue(variables.Get(variableName)));
     }
 }
Example #46
0
 static string WriteVariableDictionary(VariableDictionary variables)
 {
     var builder = new StringBuilder();
     foreach (var variable in variables.GetNames())
     {
         builder.AppendLine("    this[" + EncodeValue(variable) + "] = " + EncodeValue(variables.Get(variable)) + ";");
     }
     return builder.ToString();
 }
Example #47
0
        public void ShouldSetMachineIndexedOutputVariables()
        {
            var variables = new VariableDictionary();
            variables.Set(SpecialVariables.Action.Name, "run-script");
            variables.Set(SpecialVariables.Machine.Name, "App01");

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

            Assert.AreEqual("World!", variables.Get("Octopus.Action[run-script].Output[App01].TestA"));
        }
        void EnsureVariablesSet(string workingDirectory, VariableDictionary variables)
        {
            // If the certificate-file exists, we assume all variables have also been set
            if (EnsureCertificateFileExists(workingDirectory, variables))
                return;

            Log.SetOutputVariable(SpecialVariables.Action.Azure.Output.ModulePath, azurePowershellModulePath, variables);
            Log.SetOutputVariable(SpecialVariables.Action.Azure.Output.SubscriptionId, variables.Get(SpecialVariables.Action.Azure.SubscriptionId), variables);
            // Use the account-name configured in Octopus as the subscription-data-set name
            Log.SetOutputVariable(SpecialVariables.Action.Azure.Output.SubscriptionName, variables.Get(SpecialVariables.Account.Name), variables);
        }
Example #49
0
 static void WriteScriptModules(VariableDictionary variables, StringBuilder output)
 {
     foreach (var variableName in variables.GetNames().Where(SpecialVariables.IsLibraryScriptModule))
     {
         var name = "Library_" + new string(SpecialVariables.GetLibraryScriptModuleName(variableName).Where(char.IsLetterOrDigit).ToArray()) + "_" + DateTime.Now.Ticks;
         output.Append("New-Module -Name ").Append(name).Append(" -ScriptBlock {");
         output.AppendLine(variables.Get(variableName));
         output.AppendLine("} | Import-Module");
         output.AppendLine();
     }
 }