> For the complete documentation index, see [llms.txt](https://thorstenkramm.gitbook.io/saltstack/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://thorstenkramm.gitbook.io/saltstack/eigene-module-erstellen.md).

# Eigene Module erstellen

### Eigene Module anlegen, ein simples Beispiel

#### Modul auf dem Master anlegen

Salt-Module sind Python-Dateien, die auf dem Minion ausgeführt werden. Leg die Datei im Verzeichnis `/srv/salt/_modules/` ab. Hier ein einfaches Beispiel:

{% code title="/srv/salt/\_modules/geoip.py" %}

```python
import requests

def get_location():
    """
    Holt den Standort des Minions basierend auf der öffentlichen IP.
    """
    url = "http://ip-api.com/json/"
    try:
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            return {
                "country": data.get("country"),
                "region": data.get("regionName"),
                "city": data.get("city"),
                "latitude": data.get("lat"),
                "longitude": data.get("lon"),
            }
        else:
            return {"error": "API request failed with status code {}".format(response.status_code)}
    except Exception as e:
        return {"error": str(e)}
```

{% endcode %}

#### Module auf Minions kopieren

Kopieren Sie das Modul auf alle Minions. Dies müssen Sie nach jeder Änderung wiederholen.

`salt '*' saltutil.sync_modules`

#### Modul verwenden

`salt '*' geoip.get_location`

#### Modul in einem State verwenden

```
get_minion_location:
  module.run:
    - name: geoip.get_location
```

### Das eigene Monitoring Modul, die KI hilft

Nutzen Sie die KI, z. B. ChatGPT, um sich eigene Module erstellen zu lassen. Hier ein Beispielprompt:

<details>

<summary>ChatGPT Prompt</summary>

Erstelle ein Salt Modul „uptime\_monitor“ mit der Funktion „create“ basierend auf Python3 und dem Requests Modul. Das Modul soll mit der API von Betterstack Uptime Monitoring kommunizieren. <https://uptime.betterstack.com/api/v2/heartbeats>

Das Modul soll einen Heartbeat Monitor erstellen, damit der Minion per curl einen Heartbeat senden kann.&#x20;

#### Parameter

Das Modul erwartet die Angabe der folgenden Parameter

* "api\_key" Key zur Authentifizierung an der API, verpflichtend
* &#x20;„monitor“. Der Wert von "monitor" wird bei Betterstack als Name des Heartbeat Monitors gesetzt. Pflichtangabe
* "env\_file". Angabe einer Datei. optional. Wenn Datei angeben, wird die URL des Hartbeats Monitors als Shell Variable, in diese Datei gespeichert. Z.B. MONITOR\_URL="<https://example.com>"
* "env\_var", Name der Umgebungsvariable für "env\_file". Optional. Standard "MONITOR\_URL".&#x20;
* „grace“. Default = 5 Minuten. optional
* &#x20;„period“. Default = 1 Minute. optional

#### Rückgabe

Das Modul soll die URL des Heartbeat Monitors zurückliefen. Wenn der Heartbeat Monitor schon existiert, soll die existierende URL und keine Änderungen zurückgeliefert werden.&#x20;

#### Fehlerbehandlung

Sollte die API nicht 2XX zück liefern, verpacke die Antwort der API in eine sauber formatierte und gut lesbare Fehlermeldung. Beachte, dass eine Fehlermeldung der API Json oder Plaintext sein kann.

</details>

<figure><img src="/files/zwC7DLoFiBgwDZB9nw0L" alt=""><figcaption><p>ChatGPT erstellt ein Salt Modul für uns.</p></figcaption></figure>

```
salt '*' saltutil.sync_modules
salt 'ruby' uptime_monitor.create api_key='**********' monitor='una'
```

<figure><img src="/files/v1rVmvXDf5WfLqc8mg1x" alt=""><figcaption><p>Das Modul hat den Heartbeat Monitor angelegt</p></figcaption></figure>

```yaml
# Create the heartbeat monitor and store the URL in the Minion's grains
create_heartbeat_monitor:
  module.run:
    - name: uptime_monitor.create
    - api_key: ********
    - monitor: {{ grains['id'] }}
    - env_file: /etc/default/uptime_monitor

# Call the URL to send a heartbeat
sned_heartbeat:
  cmd.run: 
    - name: |
        cat /etc/default/uptime_monitor
        . /etc/default/uptime_monitor
        curl -s $MONITOR_URL
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://thorstenkramm.gitbook.io/saltstack/eigene-module-erstellen.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
