> ## Documentation Index
> Fetch the complete documentation index at: https://doc.qbilon.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Creating Custom Tasks

> Create custom task implementations and package them for execution.

## Preface

The sequence of tasks will commence with a rudimentary custom task, progressing to one that interacts with the Qbilon API. Finally, the program will report findings directly from Qbilon to the user's designated MS Teams channel.

## Prerequisites

There are some prerequisites to complete the following tutorial steps:

* a [Docker Hub](https://hub.docker.com/) account,
* a code editor, e.g., [Visual Studio Code](https://code.visualstudio.com/) and
* [Docker Desktop](https://www.docker.com/products/docker-desktop/) installed on the local machine.

## Hello Qbilon!

The first task is the classic "Hello World" program:

1. To do this, create a new folder on your machine and put an `app.mjs` file inside it. Open the blank file in VS Code and add the following line of code:
   ```javascript theme={null}
   console.log("Hello Qbilon!");
   ```
2. Create an additional file called `Dockerfile` in the same folder. Open this file in VS Code as well, and add the following content:
   ```text theme={null}
   FROM node:24-alpine
   WORKDIR /usr/src/app
   COPY app.mjs ./
   CMD ["node", "app.mjs"]
   ```
3. Create a new repository at [Docker Hub](https://hub.docker.com/) and remember its full name. It is usually in the form `<username>/<repositoryname>`, e.g., `qbilon/qb-hello-qbilon`.
4. Open a terminal in the same folder where you created the above files. To build a local Docker image out of your code and the Docker file, use the following command:
   ```bash theme={null}
   docker build "--platform=linux/amd64" -t "<your repository>:<tag>" .
   ```

The `<your repository>` part would be the `<username>/<repositoryname>` combination mentioned above, and the `tag` is usually a freely chosen "version." For now, an example could be `qbilon/qb-hello-qbilon:v1`.

5. Now that a local Docker image was built, it can be pushed to the public Docker Hub repository so Qbilon can find it. To do so, execute the following command in the same terminal as before:

```bash theme={null}
 docker push <your repository>:<tag>
```

In order to make it available and use it in Qbilon, just follow the instructions in the [Managing Custom Tasks](https://doc.qbilon.io/12-customizing-qbilon/custom-tasks/managing-custom-tasks.md) documentation.

The task will not produce any output because the logs created will not be visible in Qbilon's UI. In the next section, we will focus on how to interact with Qbilon to achieve such effects.

## Logging to Qbilon

The second custom task will focus on generating an actual log output in Qbilon to show that a task is working properly.

To do this, follow these steps:

1. Change the code of your `app.mjs` to the following:

```javascript theme={null}
import { readFileSync } from 'node:fs';

// Read the connection details and token provided by Qbilon.
const host = process.env.QB_HOST.replace(/\/+$/, '');
const taskId = encodeURIComponent(process.env.QB_TASK_ID);
const token = readFileSync('/tmp/task-authentication', 'utf8').trim();

// Send a log entry that appears in the task details in Qbilon.
await fetch(`${host}/apiv1/tasks/${taskId}/log`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    logLevel: 'Info',
    errorCode: 200,
    title: 'Hello Qbilon!',
    description: 'Just wanted to say hello :)'
  })
});
```

2. A new repository can be created on Docker Hub for this adopted project, or an old one can be reused by repeating the commands from the "Hello Qbilon" section to upload an updated version of the code.
3. Creating a task template from this image in Qbilon, generating a task for it and letting it run will result in the following output appearing in the details section:

![Creating Custom Tasks: Logging to Qbilon](https://mintcdn.com/qbilon-docs/Jmla3tEw4FRYjkNT/.gitbook/assets/ab4db997-eb69-41a7-bf17-ed385888b26b-image.png?fit=max\&auto=format\&n=Jmla3tEw4FRYjkNT\&q=85\&s=385d2fe194ace3d296d1f73501c793f1)

## Creating Custom Reports

Producing visible output with a custom task enables the utilization of this data via the [Read API](https://doc.qbilon.io/12-customizing-qbilon/rest-api/reading-from-qbilon.md). For the sake of this example, we will assume that the objective is to report all Azure Virtual Machines and AWS EC2 instances that Qbilon has detected within the last 24 hours to a Microsoft Teams channel.

Use the Workflows app in Microsoft Teams to create an incoming webhook. The retired Office 365 Connectors setup is no longer supported.

1. Open Workflows in Microsoft Teams.
2. Choose the channel webhook template "Send webhook alerts to a channel", or the equivalent "Post to a channel when a webhook request is received" template available in your tenant.
3. Select the target team and channel, sign in to the required connection, and save the workflow.
4. For this example, configure the webhook trigger to allow requests from "Anyone". The example authenticates to the workflow by possessing its secret URL; it does not obtain a Microsoft Entra token. Use this option only if permitted by your organization's policies. A tenant-only trigger requires additional Entra authentication that is outside this example.
5. Copy the generated webhook URL. Keep it secret, do not commit it to source control, and do not include it in task logs.
6. The replacement script sends an Adaptive Card message with an attachments array. Use a workflow that accepts this request format. A custom workflow that expects a different body must be adapted accordingly.

| Display Name | Variable Name | Type | Required | Value |
| - | - | - | - | - |
| Asset type | `TYPE` | String | Yes | `Azure Virtual Machine` or `AWS EC2`, exactly as named in your Qbilon schema |
| Teams workflow webhook | `WEBHOOK` | String (Secret) | Yes | The generated HTTPS URL of the Teams workflow |

Configure WEBHOOK as a secret string, even if an older screenshot shows a URL parameter. One task instance queries one asset type. To report both Azure virtual machines and AWS EC2 instances, create two task instances from this template: one with TYPE set to Azure Virtual Machine and one with TYPE set to AWS EC2. Both may use the same Teams workflow webhook. Qbilon injects QB\_HOST and QB\_TASK\_ID automatically; do not add these as custom configuration parameters.
[support.microsoft.com](https://support.microsoft.com/en-us/workflows/send-messages-in-teams-using-incoming-webhooks)

Next steps:

1. Now that everything is set up, change the code in your `app.mjs` file to the following:

```javascript theme={null}
import { readFileSync } from 'node:fs';

// Qbilon provides the host, task parameters and authentication file.
const host = process.env.QB_HOST.replace(/\/+$/, '');
const type = process.env.TYPE;
const token = readFileSync('/tmp/task-authentication', 'utf8').trim();

// 1. Query assets first seen in the last 24 hours.
const query = {
  types: [
    {
      names: [type],
      attributeNames: ['Name'],
      condition: {
        conditionType: 'atomic',
        attributeName: 'First Seen',
        operator: 'within',
        value: '-P1DT'
      }
    }
  ]
};

const response = await fetch(`${host}/apiv1/data`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(query)
});
const data = await response.json();
const elements = data.types[type]?.elements ?? [];
const names = elements.map(element => `- ${element.properties.Name}`).join('\n');

// 2. Put the asset names into an Adaptive Card for Teams Workflows.
const message = {
  type: 'message',
  attachments: [
    {
      contentType: 'application/vnd.microsoft.card.adaptive',
      content: {
        type: 'AdaptiveCard',
        version: '1.2',
        body: [{
          type: 'TextBlock',
          text: `${type} assets first seen in the last 24 hours:\n${names || 'No matching assets.'}`,
          wrap: true
        }]
      }
    }
  ]
};

// 3. Send the card.
await fetch(process.env.WEBHOOK, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(message)
});
```

2. There are no changes needed in the Docker file as no additional libraries are used.
3. It is possible to update the existing image in an individual repository or create a new one and push it there.
4. When creating a custom task template for the image, two additional configuration parameters should be created:

![Creating Custom Tasks: Creating Custom Reports](https://mintcdn.com/qbilon-docs/Jmla3tEw4FRYjkNT/.gitbook/assets/ab149556-d14c-46a4-8792-0b236116aa8c-parameters.png?fit=max\&auto=format\&n=Jmla3tEw4FRYjkNT\&q=85\&s=a070dfe8a1f6ec6287f347abf5afa7d4)

5. A new automation can now be created for this task. Please use the MS Teams Webhook URL from before. Subsequently, the following message is received in the "Qbilon Showcase" channel:

![Creating Custom Tasks: Creating Custom Reports](https://mintcdn.com/qbilon-docs/lr-P4KF_9wn8x9Vs/.gitbook/assets/de576793-6dfd-4907-bf36-6403d366db67-image.png?fit=max\&auto=format\&n=lr-P4KF_9wn8x9Vs\&q=85\&s=70dd69a5347aafecfd6432ce679539ae)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.