Tuesday, November 15, 2022

Azure @ Enterprise - Scheduling task inside Windows container in Kubernetes

Problem

As part of my day job, we are doing a lift & shift of a giant monolith .NET 4.8 Windows-based application to Azure Kubernetes Service. Currently the application supports scheduling tasks that can be created and configured by the admins. Behind the scene, it creates scheduled tasks in Windows Task Scheduler pointing to the respective executable and passing right parameters.

How to do this in AKS or Kubernetes in general?

Solution

Since we need to limit the changes, we are planning to use the Windows task scheduler inside the container. Yes, it is going to be a Windows container and it may not be the most innovative solution in the world of containers where containers may be destroyed and recreated at any time.

Keeping the design things aside, this post is to explain how the Windows scheduled tasks can be created inside the container.

Nothing fancy, the same command that works inside a virtual machine to create a scheduled task will work inside Windows containers as well. Below goes the command.

schtasks /create /sc minute /mo 1 /tn "test-task" /tr "C:\path\to\scheduleRunner.exe" /ST 17:30 /ru SYSTEM 

Hope the command is explanatory. The task run under the SYSTEM account.

If this command is used inside the Dockerfile, we have to worry about the escaping of quotes. So better use the XML file-based task creation. There will be an XML file with all the task creation parameters. The command just uses that XML file.

schtasks.exe /Create /XML task.xml /tn test-task

Read the docs to get the full XML schema. 

Dockefile

Below is the docker instruction to create the task. In the production case, the tasks will be created on demand instead of statically at the time of docker image creation.

RUN schtasks.exe /Create /XML c:\\task.xml /tn test-task

Sample repo

A working sample that creates PowerShell-based task action can be found at the below location. PRs are welcome, if you find any issues or have a suggestion to improve.

Points to note

When we schedule tasks in production systems, they may be running in the context of a service account to access protected resources such as database. To my understanding that is supported if we can domain join containers. Domain joining containers and all is itself a big topic so limiting this post to the creation of scheduled tasks inside the Windows container.

It just works. No challenge. Hopefully, next time will come up with a challenging problem.

No comments: