public ConDepNoRunbookTierDefinedException(Runbook application, ConDepSettings settings) : base(string.Format("No Tiers defined for application {0}. You need to specify a tier using the {1} attribute on the {0} class. Tiers available in your configuration are {2}.", application.GetType().Name, typeof(TierAttribute).Name, string.Join(", ", settings.Config.Tiers.Select(x => x.Name)))) { }
public Runbook CreateRunbookByPath(string automationAccountName, string runbookPath, string description, string[] tags) { Runbook runbook = this.CreateRunbook(automationAccountName, File.OpenRead(runbookPath)); this.UpdateRunbook(automationAccountName, runbook.Id, description, tags, null, null, null); return(this.GetRunbook(automationAccountName, runbook.Id)); }
public async Task UpdateTARunbookAsync(Runbook taRunbook) { var requestUrl = this.CreateRequestUri(RunPowerShellClient.AdminTARunbooks); var response = await this.httpClient.PutAsJsonAsync <Runbook>(requestUrl.ToString(), taRunbook); response.EnsureSuccessStatusCode(); }
private RunbookDefinition UpdateRunbookDefinition(string automationAccountName, Guid runbookId, Stream runbookStream, bool overwrite) { var runbook = new Runbook(this.GetRunbookModel(automationAccountName, runbookId, false)); if (runbook.DraftRunbookVersionId.HasValue && overwrite == false) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.RunbookAlreadyHasDraft)); } Guid draftRunbookVersionId = runbook.DraftRunbookVersionId.HasValue ? runbook.DraftRunbookVersionId.Value : this.EditRunbook(automationAccountName, runbook.Id); var getRunbookDefinitionResponse = this.automationManagementClient.RunbookVersions.GetRunbookDefinition( automationAccountName, draftRunbookVersionId.ToString()); this.automationManagementClient.RunbookVersions.UpdateRunbookDefinition( automationAccountName, new AutomationManagement.Models.RunbookVersionUpdateRunbookDefinitionParameters { ETag = getRunbookDefinitionResponse.ETag, RunbookVersionId = draftRunbookVersionId.ToString(), RunbookStream = runbookStream, }); IEnumerable <RunbookDefinition> runbookDefinitions = this.ListRunbookDefinitionsByRunbookVersionId(automationAccountName, draftRunbookVersionId, true); return(runbookDefinitions.First()); }
public static IAsyncResult BeginStartRunbook(this Runbook runbook, OrchestratorApi orchestratorApi, AsyncCallback callback, object state, List <NameValuePair> jobParameters = null) { return(ActionExtensions.BeginRunbookAction <Guid>(runbook, orchestratorApi, "Start", callback, state, new OperationParameter[] { new BodyOperationParameter("parameters", jobParameters) })); }
public bool HasDependenciesDefined(Runbook artifact) { var typeName = typeof(IDependOn <>).Name; var interfaces = artifact.GetType().GetInterfaces(); return(interfaces.Any(x => x.Name == typeName)); }
private static void ValidateApplicationTier(Runbook runbook, ConDepSettings settings) { var hasTier = runbook.GetType().GetCustomAttributes(typeof(TierAttribute), false).Any(); if (!hasTier) throw new ConDepNoRunbookTierDefinedException(runbook, settings); var hasSingleTier = runbook.GetType().GetCustomAttributes(typeof(TierAttribute), false).SingleOrDefault() != null; if (!hasSingleTier) throw new ConDepNoRunbookTierDefinedException(String.Format("Multiple tiers defined for {0}. Only one tier is allowed by Artifact.", runbook.GetType().Name)); }
public TARunbookModel(Runbook taRunbook) { this.RunbookId = taRunbook.RunbookId; this.RunbookName = taRunbook.RunbookName; this.RunbookTag = taRunbook.RunbookTag; this.PlanId = taRunbook.PlanId; this.PlanName = taRunbook.PlanName; this.Type = "TARunbook"; }
protected override void AutomationExecuteCmdlet() { Runbook runbook = null; // ByRunbookName runbook = this.AutomationClient.CreateRunbookByName( this.ResourceGroupName, this.AutomationAccountName, this.Name, this.Description, this.Tags, this.Type, this.LogProgress, this.LogVerbose, false); this.WriteObject(runbook); }
public void UpdateRunbook(Runbook runbook) { AutomationClient.Runbook.Update(ResourceGroup, AutomationAccount, runbook.Name, new RunbookUpdateParameters { Name = runbook.Name, Description = runbook.Description, LogProgress = runbook.LogProgress, LogVerbose = runbook.LogVerbose }); }
/// <summary> /// Start Runbook with the the given Runbook and list of NameValuepair parameters /// </summary> /// <param name="runbook"></param> /// <param name="parameters"></param> /// <returns></returns> private RunbookJob StartRunBook(Runbook runbook, List <NameValuePair> parameters) { //try //{ IgnoreCertificate(); #region Setting up parameters for runbook OperationParameter operationParameters = new BodyOperationParameter(JobParameterName, parameters); #endregion Setting up parameters for runbook ValidateParameters(runbook, parameters); #region Create runbook job // Format the uri var uri = string.Concat(api.Runbooks, string.Format("(guid'{0}')/{1}", runbook.RunbookID, StartRunbookActionName)); var uriSMA = new Uri(uri, UriKind.Absolute); var jobIdValue = api.Execute <Guid>(uriSMA, HttpPost, true, operationParameters) as QueryOperationResponse <Guid>; var jobId = jobIdValue.Single(); var job = api.Jobs.Where(j => j.JobID == jobId).First(); if (job == null) { return(new RunbookJob { OutputMessage = "Job not started!" }); } else { return(new RunbookJob { Id = jobId, OutputMessage = String.Format("Job Started. JobID: {0}, JobStatus: {1}", jobId, job.JobStatus) }); } #endregion Create runbook job // } //catch (DataServiceQueryException ex) //{ // throw new ApplicationException("Error starting runbook.", ex); //} }
public Runbook CreateRunbookByName(string automationAccountName, string runbookName, string description, string[] tags) { var runbookScript = string.Format(CultureInfo.InvariantCulture, @"workflow {0}{1}{{{1}}}", runbookName, Environment.NewLine); using (var streamReader = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(runbookScript), false), Encoding.UTF8)) { Stream runbookStream = streamReader.BaseStream; Runbook runbook = this.CreateRunbook(automationAccountName, runbookStream); this.UpdateRunbook(automationAccountName, runbook.Id, description, tags, null, null, null); return(this.GetRunbook(automationAccountName, runbook.Id)); } }
public void UpdateRunbook(Runbook runbook) { AutomationClient.Runbooks.Update(automationAccount, new RunbookUpdateParameters { Name = runbook.Name, Properties = new RunbookUpdateProperties { Description = runbook.Properties.Description, LogProgress = runbook.Properties.LogProgress, LogVerbose = runbook.Properties.LogVerbose } }); }
public void UpdateRunbook(Runbook runbook) { AutomationClient.Runbooks.Patch(resourceGroup, automationAccount, new RunbookPatchParameters { Name = runbook.Name, Properties = new RunbookPatchProperties { Description = runbook.Properties.Description, LogProgress = runbook.Properties.LogProgress, LogVerbose = runbook.Properties.LogVerbose } }); }
private IEnumerable <RunbookParameter> ListRunbookParameters(string automationAccountName, Guid runbookId) { Runbook runbook = this.GetRunbook(automationAccountName, runbookId); if (!runbook.PublishedRunbookVersionId.HasValue) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.RunbookHasNoPublishedVersionById, runbookId)); } return(this.automationManagementClient.RunbookParameters.ListByRunbookVersionId( automationAccountName, runbook.PublishedRunbookVersionId.Value.ToString()).RunbookParameters.Select(runbookParameter => new RunbookParameter(runbookParameter))); }
//Runbook exists both on disk and in the cloud. But are they in sync? public AutomationRunbook(FileInfo localFile, Runbook cloudRunbook, RunbookDraft cloudRunbookDraft) : base(cloudRunbook.Name, localFile.LastWriteTime, cloudRunbook.Properties.LastModifiedTime.LocalDateTime) { this.AuthoringState = cloudRunbook.Properties.State; this.localFileInfo = localFile; this.Description = cloudRunbook.Properties.Description; this.Parameters = cloudRunbook.Properties.Parameters; if (cloudRunbookDraft != null) { this.LastModifiedCloud = cloudRunbookDraft.LastModifiedTime.LocalDateTime; UpdateSyncStatus(); } }
/// <summary> /// validating parameters of Runbook /// </summary> /// <param name="runbook"></param> /// <param name="parameters"></param> private void ValidateParameters(Runbook runbook, List <NameValuePair> parameters) { var pamts = GetRunbookParameters(runbook.PublishedRunbookVersionID) as IEnumerable <SMARunbookParameter>; var lstErrors = new List <ParameterError>(); foreach (var val in parameters) { var param = pamts.Where(p => p.Name == val.Name).FirstOrDefault(); if (param == null) { lstErrors.Add(new ParameterError { Parameter = new SMARunbookParameter { Name = val.Name, Value = val.Value }, ErrorMessage = "Parameter does not exist." }); } else { var type = Type.GetType(param.Type); var result = ConvertType(val.Value, type); if (param.Type == "System.Management.Automation.SwitchParameter") { result = val.Value; } if (result == null) { lstErrors.Add(new ParameterError { Parameter = new SMARunbookParameter { Name = val.Name, Value = val.Value }, ErrorMessage = String.Format("This parameter expects value of type {0}.The passed value cannot be converted to {0}." , param.Type) }); } } } if (lstErrors.Count > 0) { throw new ParameterException(lstErrors); } }
/// <summary> /// Return RunbookGenerated type with common properties and parameter definitions. Resource Group Name and Automation Account Name specified from user input (ex. directly in URL) /// </summary> public async Task <IRunbookGenerated> GetRunbookGenerated(string resourceGroupName, string automationAccountName, string runbookName) { //Get runbook Runbook runbook = await GetRunbook(resourceGroupName, automationAccountName, runbookName); var runbookGenerated = new RunbookGenerated { Name = runbookName, DisplayName = runbook.Tags.Where(tag => tag.Key == _automationTagDisplayName.Key).FirstOrDefault().Value, HybridWorkerGroup = runbook.Tags.Where(tag => tag.Key == _automationTagHybridWorkerGroup.Key).FirstOrDefault().Value, ParameterDefinitions = await GetRunbookParameterDefinitions(resourceGroupName, automationAccountName, runbook) }; return(runbookGenerated); }
private static void ValidateApplicationTier(Runbook runbook, ConDepSettings settings) { var hasTier = runbook.GetType().GetCustomAttributes(typeof(TierAttribute), false).Any(); if (!hasTier) { throw new ConDepNoRunbookTierDefinedException(runbook, settings); } var hasSingleTier = runbook.GetType().GetCustomAttributes(typeof(TierAttribute), false).SingleOrDefault() != null; if (!hasSingleTier) { throw new ConDepNoRunbookTierDefinedException(String.Format("Multiple tiers defined for {0}. Only one tier is allowed by Artifact.", runbook.GetType().Name)); } }
private static IAsyncResult BeginRunbookAction <TElement>(Runbook runbook, OrchestratorApi orchestratorApi, string action, AsyncCallback callback, object state, params OperationParameter[] operationParameters) { if (runbook == null || runbook.RunbookID == Guid.Empty) { throw new ArgumentNullException("runbook"); } if (orchestratorApi == null) { throw new ArgumentNullException("orchestratorApi"); } if (!ActionExtensions.RunbookActions.Contains(action)) { throw new ArgumentOutOfRangeException("action", action, "An invalid Runbook action was requested."); } return(orchestratorApi.BeginExecute <TElement>(ActionExtensions.GetActionUri(orchestratorApi.Runbooks.RequestUri, runbook.RunbookID, action), callback, state, "POST", true, operationParameters)); }
public IEnumerable<ServerConfig> GetServers(Runbook runbook, ConDepSettings settings) { if (settings.Config.UsingTiers) { ValidateApplicationTier(runbook, settings); var tier = runbook.GetType().GetCustomAttributes(typeof(TierAttribute), false).Single() as TierAttribute; if (!settings.Config.Tiers.Exists(tier.TierName)) { throw new ConDepTierDoesNotExistInConfigException(string.Format("Tier {0} does not exist in {1}.env.config", tier.TierName, settings.Options.Environment)); } return settings.Config.Tiers.Single(x => x.Name.Equals(tier.TierName, StringComparison.OrdinalIgnoreCase)) .Servers; } return settings.Config.Servers; }
private static Runbook GetRunbookByPath(string serviceURL, string path) { Runbook runbook = null; SCOService.OrchestratorContext context = new SCOService.OrchestratorContext(new Uri(serviceURL)); // Set credentials to default or a specific user. context.Credentials = System.Net.CredentialCache.DefaultCredentials; // Get the runbook based on the entered path runbook = context.Runbooks.Where(rb => { return(rb.Path == path); }).First(); return(runbook); }
public IEnumerable <ServerConfig> GetServers(Runbook runbook, ConDepSettings settings) { if (settings.Config.UsingTiers) { ValidateApplicationTier(runbook, settings); var tier = runbook.GetType().GetCustomAttributes(typeof(TierAttribute), false).Single() as TierAttribute; if (!settings.Config.Tiers.Exists(tier.TierName)) { throw new ConDepTierDoesNotExistInConfigException(string.Format("Tier {0} does not exist in {1}.env.config", tier.TierName, settings.Options.Environment)); } return (settings.Config.Tiers.Single(x => x.Name.Equals(tier.TierName, StringComparison.OrdinalIgnoreCase)) .Servers); } return(settings.Config.Servers); }
public static IAsyncResult BeginStartOnSchedule(this Runbook runbook, OrchestratorApi orchestratorApi, AsyncCallback callback, object state, Schedule schedule, List <NameValuePair> jobParameters = null) { if (schedule == null) { throw new ArgumentNullException("schedule"); } if (schedule.ScheduleID == Guid.Empty) { orchestratorApi.AddToSchedules(schedule); orchestratorApi.SaveChanges(); } return(ActionExtensions.BeginRunbookAction <Guid>(runbook, orchestratorApi, "StartOnSchedule", callback, state, new OperationParameter[] { new BodyOperationParameter("parameters", jobParameters), new BodyOperationParameter("scheduleId", schedule.ScheduleID) })); }
protected override void AutomationProcessRecord() { Runbook runbook = null; // ByRunbookName runbook = this.AutomationClient.CreateRunbookByName( this.ResourceGroupName, this.AutomationAccountName, this.Name, this.Description, this.Tags, RunbookTypeSdkValue.Resolve(this.Type), this.LogProgress, this.LogVerbose, false); this.WriteObject(runbook); }
/// <summary> /// Initializes a new instance of the <see cref="FileServerModel" /> class. /// </summary> /// <param name="ProductModel">The domain name from API.</param> public RunbookModel(Runbook runbookFromApi) { this.RunbookId = runbookFromApi.RunbookId; this.RunbookName = runbookFromApi.RunbookName; this.RunbookTag = runbookFromApi.RunbookTag; this.LastJobStatus = runbookFromApi.LastJobStatus; this.LastJobStart = runbookFromApi.LastJobStart; this.PlanId = runbookFromApi.PlanId; this.PlanName = runbookFromApi.PlanName; this.SubscriptionId = runbookFromApi.SubscriptionId; this.ParamString = runbookFromApi.ParamString; this.ParamInt = runbookFromApi.ParamInt; this.ParamStringArray = runbookFromApi.ParamStringArray; this.ParamDate = runbookFromApi.ParamDate; this.ParamBool = runbookFromApi.ParamBool; this.ParamVMs = runbookFromApi.ParamVMs; this.Type = "Runbook"; }
//public void PopulateWithDependencies(Runbook runbook, ConDepSettings settings) //{ // if (!HasDependenciesDefined(runbook)) return; // runbook.Dependencies = GetDependeciesForRunbook(runbook, settings); //} public List<Runbook> GetDependeciesForRunbook(Runbook runbook, ConDepSettings settings) { var typeName = typeof(IDependOn<>).Name; var typeInterfaces = runbook.GetType().GetInterfaces(); var dependencies = typeInterfaces.Where(x => x.Name == typeName); var dependencyInstances = new List<Runbook>(); foreach (var infraInterface in dependencies) { var dependencyType = infraInterface.GetGenericArguments().Single(); var dependencyInstance = settings.Options.Assembly.CreateInstance(dependencyType.FullName) as Runbook; dependencyInstances.AddRange(new RunbookDependencyHandler().GetDependeciesForRunbook(dependencyInstance, settings)); dependencyInstances.Add(dependencyInstance); } return dependencyInstances; }
protected override void AutomationExecuteCmdlet() { Runbook runbook = null; if (this.ParameterSetName == AutomationCmdletParameterSets.ByPath) { // ByRunbookPath runbook = this.AutomationClient.CreateRunbookByPath( this.AutomationAccountName, this.ResolvePath(this.Path), this.Description, this.Tags); } else if (this.ParameterSetName == AutomationCmdletParameterSets.ByRunbookName) { // ByRunbookName runbook = this.AutomationClient.CreateRunbookByName( this.AutomationAccountName, this.Name, this.Description, this.Tags); } this.WriteObject(runbook); }
// main program static void Main(string[] args) { // Begin change values string serviceURL = "http://*****:*****@"\4.DTEK PROJECTS\LAUNCH-TEST\CS-LAUNCH01"; Hashtable parameters = new Hashtable(); parameters["recipient"] = "*****@*****.**"; parameters["message"] = "Launched CSLAUNCH01 runbook"; // End change values Runbook runbook = GetRunbookByPath(serviceURL, runbookPath); List <RunbookParameter> runbookParameters = GetRunbookParametersById(serviceURL, runbook.Id); Job job = StartRunbookJob(serviceURL, runbook.Id, runbookParameters, parameters); Console.WriteLine("Successfully started runbook. Job ID: {0}", job.Id.ToString()); Console.ReadKey(); }
//public void PopulateWithDependencies(Runbook runbook, ConDepSettings settings) //{ // if (!HasDependenciesDefined(runbook)) return; // runbook.Dependencies = GetDependeciesForRunbook(runbook, settings); //} public List <Runbook> GetDependeciesForRunbook(Runbook runbook, ConDepSettings settings) { var typeName = typeof(IDependOn <>).Name; var typeInterfaces = runbook.GetType().GetInterfaces(); var dependencies = typeInterfaces.Where(x => x.Name == typeName); var dependencyInstances = new List <Runbook>(); foreach (var infraInterface in dependencies) { var dependencyType = infraInterface.GetGenericArguments().Single(); var dependencyInstance = settings.Options.Assembly.CreateInstance(dependencyType.FullName) as Runbook; dependencyInstances.AddRange(new RunbookDependencyHandler().GetDependeciesForRunbook(dependencyInstance, settings)); dependencyInstances.Add(dependencyInstance); } return(dependencyInstances); }
public void AddToRunbooks(Runbook runbook) { base.AddObject("Runbooks", runbook); }
public static Runbook CreateRunbook(global::System.Guid tenantID, global::System.Guid runbookID, string runbookName, global::System.DateTime creationTime, global::System.DateTime lastModifiedTime, bool isApiOnly, bool isGlobal, bool logDebug, bool logVerbose, bool logProgress) { Runbook runbook = new Runbook(); runbook.TenantID = tenantID; runbook.RunbookID = runbookID; runbook.RunbookName = runbookName; runbook.CreationTime = creationTime; runbook.LastModifiedTime = lastModifiedTime; runbook.IsApiOnly = isApiOnly; runbook.IsGlobal = isGlobal; runbook.LogDebug = logDebug; runbook.LogVerbose = logVerbose; runbook.LogProgress = logProgress; return runbook; }
public bool HasDependenciesDefined(Runbook artifact) { var typeName = typeof(IDependOn<>).Name; var interfaces = artifact.GetType().GetInterfaces(); return interfaces.Any(x => x.Name == typeName); }
public void DeleteRunbook(string automationAccountName, string runbookName) { Runbook runbook = this.GetRunbook(automationAccountName, runbookName); this.DeleteRunbook(automationAccountName, runbook.Id); }
/// <summary> /// Returns a dictionary of parameter settings from the runbook where key is the parameter name and value is parameter setting model /// </summary> /// <param name="resourceGroup"></param> /// <param name="automationAccount"></param> /// <param name="runbookName"></param> /// <returns></returns> public async Task <Dictionary <string, RunbookParameterSetting> > GetRunbookParameterSettings(string resourceGroup, string automationAccount, string runbookName) { //Get runbook powershell content string runbookContent = (await GetContentWithHttpMessagesAsync(resourceGroup, automationAccount, runbookName)).Body; //Get runbook Runbook runbook = await GetRunbook(resourceGroup, automationAccount, runbookName); //Get sorted runbook parameters IOrderedEnumerable <KeyValuePair <string, RunbookParameter> > runbookParameters = runbook.Parameters.OrderBy(o => o.Value.Position); //Create empty dictionary Dictionary <string, RunbookParameterSetting> runbookParameterSettings = new Dictionary <string, RunbookParameterSetting>(); int i = 0; foreach (KeyValuePair <string, RunbookParameter> runbookVariable in runbookParameters) { RunbookParameterSetting runbookParameterSetting = new RunbookParameterSetting() { IsRequired = (bool)runbookVariable.Value.IsMandatory, DefaultValue = runbookVariable.Value.DefaultValue }; if (runbookParameterSetting.DefaultValue != null) { runbookParameterSetting.DefaultValue = runbookParameterSetting.DefaultValue.Replace("'", ""); } ; string pattern; if (i == 0) { //First parameter configs - get everything between 'Param(' and '<nameoffirstvariable>' pattern = $@"(?s)(?<=Param\()(.*?)(?=\${runbookVariable.Key})"; } else { //Subsequent parameter configs - get everything between '<nameofpreviousvariable>' and '<nameofcurrentvariable>' pattern = $@"(?s)(?<={runbookParameters.ToList()[i - 1].Key})(.*?)(?=\${runbookVariable.Key})"; } Regex regex = new Regex(pattern); MatchCollection paramSettingsMatches = regex.Matches(runbookContent); if (paramSettingsMatches != null && paramSettingsMatches.Count > 0) { var paramSettings = paramSettingsMatches[0]; //ValidateSet - Within the specific parameter config check for ValidateSet and add it to RunbookParameterSetting instance regex = new Regex(Constants.RegexPatternValidateSet); MatchCollection matchesValidateSet = regex.Matches(paramSettings.Value); if (matchesValidateSet != null && matchesValidateSet.Count > 0) { runbookParameterSetting.ValidateSet = (matchesValidateSet[0].Value.Replace("\"", "").Replace("'", "")).Split(","); } //Alias - Within the specific parameter config check for Alias and add it to RunbookParameterSetting instance regex = new Regex(Constants.RegexPatternAlias); MatchCollection matchesAlias = regex.Matches(paramSettings.Value); if (matchesAlias != null && matchesAlias.Count > 0) { runbookParameterSetting.DisplayName = matchesAlias[0].Value.Replace("\"", "").Replace("'", ""); } } //Add to dictionary runbookParameterSettings.Add(runbookVariable.Key, runbookParameterSetting); i++; } return(runbookParameterSettings); }
public JobProperties() { Parameters = new Dictionary<string, object>(); Runbook = new Runbook(); }
private void CancelButton_Click(object sender, RoutedEventArgs e) { _selectedRunbook = null; Close(); }
public SMARunbookModel(Runbook smaRunbook) { this.RunbookId = smaRunbook.RunbookId; this.RunbookName = smaRunbook.RunbookName; this.RunbookTag = smaRunbook.RunbookTag; }
private void ChooseRunbook() { if (RunbooksListView.SelectedValue != null && RunbooksListView.SelectedValue is Runbook) { _selectedRunbook = ((Runbook)RunbooksListView.SelectedValue); } Close(); }
public static Runbook CreateRunbook(global::System.Guid ID, global::System.Guid folderId, string name, string createdBy, global::System.DateTime creationTime, string lastModifiedBy, global::System.DateTime lastModifiedTime, bool isMonitor, string path) { Runbook runbook = new Runbook(); runbook.Id = ID; runbook.FolderId = folderId; runbook.Name = name; runbook.CreatedBy = createdBy; runbook.CreationTime = creationTime; runbook.LastModifiedBy = lastModifiedBy; runbook.LastModifiedTime = lastModifiedTime; runbook.IsMonitor = isMonitor; runbook.Path = path; return runbook; }