Skip to content

Commit

Permalink
The creation of the json_exporter configuration has been extended. (#10)
Browse files Browse the repository at this point in the history
It is now possible to add any number of configuration elements.

Thanks to @sleepy-nols for the inspiration.
  • Loading branch information
bodsch authored Jan 17, 2025
1 parent 5adf943 commit 7d22f0e
Show file tree
Hide file tree
Showing 11 changed files with 322 additions and 19 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/push-to-ansible-galaxy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ jobs:
uses: actions/checkout@v4

- name: Deploy Ansible Galaxy Collection
uses: artis3n/ansible_galaxy_collection@v2.8.3
uses: artis3n/ansible_galaxy_collection@v2.10.1
with:
api_key: '${{ secrets.GALAXY_API_KEY }}'
17 changes: 15 additions & 2 deletions hooks/doc
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

. hooks/molecule.rc

set -x
# set -x

if [ -z "${COLLECTION_DIR}" ]
then
Expand All @@ -17,7 +17,7 @@ then
# ansible-doc --list --list_files -t module ${COLLECTION_NAMESPACE}.${COLLECTION_NAME}

ansible_modules=$(
ansible-doc --list ${COLLECTION_NAMESPACE}.${COLLECTION_NAME} --json | jq -r 'keys[]'
ansible-doc --list ${COLLECTION_NAMESPACE}.${COLLECTION_NAME} --type module --json | jq -r 'keys[]'
)

for i in ${ansible_modules}
Expand All @@ -26,6 +26,19 @@ then
PAGER='cat' ansible-doc --type module ${i}
echo ""
done

# -------------------------------------------------
ansible_filter=$(
ansible-doc --list ${COLLECTION_NAMESPACE}.${COLLECTION_NAME} --type filter --json | jq -r 'keys[]'
)

for i in ${ansible_filter}
do
# echo " - ${i}"
PAGER='cat' ansible-doc --type filter ${i}
echo ""
done

fi

exit 0
61 changes: 61 additions & 0 deletions plugins/filter/json_exporter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# python 3 headers, required if submitting to Ansible

from __future__ import (absolute_import, print_function)
__metaclass__ = type

from ansible.utils.display import Display

display = Display()


class FilterModule(object):
"""
"""

def filters(self):
return {
'convert_to_modules': self.convert_to_modules,
}

def convert_to_modules(self, data, modules={}):
"""
"""
result = None
# display.v(f"convert_to_modules({data}, {modules})")

if isinstance(modules, dict):

keys = modules.keys()

if "default" in keys:
"""
default already exists
"""
# display.v("use 'defaut' entry")

for metric_b in data:
found = False
for metric_a in modules["default"]["metrics"]:
if metric_a.get("name") == metric_b.get("name"):
metric_a.update(metric_b)
found = True
break

if not found:
modules["default"]["metrics"].append(metric_b)

else:
"""
create 'defaut' entry
"""
# display.v("create 'defaut' entry")

modules['default'] = dict()
modules['default']['metrics'] = []
modules['default']['metrics'] = data

result = modules

# display.v(f"= result: {result}")

return result
83 changes: 79 additions & 4 deletions roles/json_exporter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ Tested on

* Arch Linux
* Debian based
- Debian 10 / 11
- Ubuntu 20.10
- Debian 10 / 11 / 12
- Ubuntu 20.04 / 22.04

## Usage

```
json_exporter_version: '0.5.0'
json_exporter_version: '0.6.0'
json_exporter_release: {}
Expand All @@ -57,6 +57,8 @@ json_exporter_direct_download: false
json_exporter_service: {}
json_exporter_config: []
json_exporter_modules: {}
```

### `json_exporter_service`
Expand All @@ -74,9 +76,12 @@ json_exporter_service:
listen_address: "0.0.0.0:7979"
```
### `json_exporter_config`

> **This variable is OBSOLETE and has been replaced by `json_exporter_modules`!**

The entries of `json_exporter_config` are currently being converted to the new format.

#### defaults

```yaml
Expand Down Expand Up @@ -107,6 +112,76 @@ json_exporter_config:
last_run_status: "{[].last_run_status}"
```

### `json_exporter_modules`

All possible parameters can be found in the [original documentation](https://github.com/prometheus-community/json_exporter/blob/master/examples/config.yml).

The [tests](molecule/configured/group_vras/all/vars.yml) run with an adapted version of this configuration.


#### defaults

```yaml
json_exporter_modules: {}
```

#### example

```yaml
json_exporter_modules:
jellyfin:
headers:
Authorization: MediaBrowser Token=xxxxxxxxxxxxxxxxx
Content-Type: application/json
accept: application/json
metrics:
- name: jellyfin
type: object
help: User playback metrics from Jellyfin
path: '{ [*] }'
labels:
user_name: '{ .UserName }'
# User PromQL label_join and label_replace to concatenate
# these values into a nice item description
item_type: '{ .NowPlayingItem.Type }'
item_name: '{ .NowPlayingItem.Name }'
item_path: '{ .NowPlayingItem.Path }'
series_name: '{ .NowPlayingItem.SeriesName }'
episode_index: 'e{ .NowPlayingItem.IndexNumber }'
season_index: 's{ .NowPlayingItem.ParentIndexNumber }'
client_name: '{ .Client }'
device_name: '{ .DeviceName }'
values:
is_paused: '{ .PlayState.IsPaused }'
animals:
metrics:
- name: animal
type: object
help: Example of top-level lists in a separate module
path: '{ [*] }'
labels:
name: '{ .noun }'
predator: '{ .predator }'
values:
population: '{ .population }'
http_client_config:
tls_config:
insecure_skip_verify: true
basic_auth:
username: myuser
password: veryverysecret
# password_file: /tmp/mysecret.txt
valid_status_codes:
- 200
- 204
body:
content: !unsafe
'{"time_diff": "{{ duration `95` }}","anotherVar": "{{ .myVal | first }}"}'
templatize: true
```
You can also look at the [molecule](molecule/default/group_vars/all) test.
Expand Down
5 changes: 5 additions & 0 deletions roles/json_exporter/defaults/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ json_exporter_direct_download: false

json_exporter_service: {}

# `json_exporter_config` are OBSOLETE
# replaced by `json_exporter_modules`
# please read the documentation!
json_exporter_config: []

json_exporter_modules: {}

...
56 changes: 56 additions & 0 deletions roles/json_exporter/molecule/configured/group_vars/all/vars.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,60 @@ json_exporter_config:
last_run: "{[].last_run}"
last_run_status: "{[].last_run_status}"

json_exporter_modules:

jellyfin:
headers:
Authorization: MediaBrowser Token=xxxxxxxxxxxxxxxxx
Content-Type: application/json
accept: application/json

metrics:
- name: jellyfin
type: object
help: User playback metrics from Jellyfin
path: '{ [*] }'
labels:
user_name: '{ .UserName }'
# User PromQL label_join and label_replace to concatenate
# these values into a nice item description
item_type: '{ .NowPlayingItem.Type }'
item_name: '{ .NowPlayingItem.Name }'
item_path: '{ .NowPlayingItem.Path }'
series_name: '{ .NowPlayingItem.SeriesName }'
episode_index: 'e{ .NowPlayingItem.IndexNumber }'
season_index: 's{ .NowPlayingItem.ParentIndexNumber }'
client_name: '{ .Client }'
device_name: '{ .DeviceName }'
values:
is_paused: '{ .PlayState.IsPaused }'

# original examples from
# https://github.com/prometheus-community/json_exporter/blob/master/examples/config.yml
animals:
metrics:
- name: animal
type: object
help: Example of top-level lists in a separate module
path: '{ [*] }'
labels:
name: '{ .noun }'
predator: '{ .predator }'
values:
population: '{ .population }'
http_client_config:
tls_config:
insecure_skip_verify: true
basic_auth:
username: myuser
password: veryverysecret
# password_file: /tmp/mysecret.txt
valid_status_codes:
- 200
- 204
body:
content: !unsafe
'{"time_diff": "{{ duration `95` }}","anotherVar": "{{ .myVal | first }}"}'
templatize: true

...
27 changes: 27 additions & 0 deletions roles/json_exporter/tasks/configure.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
---

- name: warn against the use of obsolete variables
when:
- json_exporter_config | default([]) | count > 0
block:
- name: warn against the use of obsolete variables # noqa ignore-errors
ansible.builtin.fail:
msg: |
The use of `json_exporter_config` is obsolete!
Please use `json_exporter_modules` instead!
The obsolete variable is automatically converted internally.
The conversion will be removed in one of the next releases!
ignore_errors: true

- name: wait 5 seconds to realise the message
delegate_to: localhost
ansible.builtin.wait_for:
timeout: 10

- name: convert obsolete variable ...
ansible.builtin.set_fact:
json_exporter_modules: "{{ json_exporter_config | bodsch.prometheus.convert_to_modules(json_exporter_modules) }}"
json_exporter_config: []

- name: merge json_exporter configuration between defaults and custom
ansible.builtin.set_fact:
json_exporter_modules: "{{ json_exporter_defaults_modules | combine(json_exporter_modules, recursive=True) }}"

- name: create json_exporter configuration directory
ansible.builtin.file:
path: "{{ json_exporter_config_dir }}"
Expand Down
23 changes: 23 additions & 0 deletions roles/json_exporter/tasks/main.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
---

# - name: warn against the use of obsolete variables
# when:
# - json_exporter_config | default([]) | count > 0
# block:
# - name: warn against the use of obsolete variables # noqa ignore-errors
# ansible.builtin.fail:
# msg: |
# The use of `json_exporter_config` is obsolete!
# Please use `json_exporter_modules` instead!
# The obsolete variable is automatically converted internally.
# The conversion will be removed in one of the next releases!
# ignore_errors: true
#
# # - name: wait 5 seconds to realise the message
# # delegate_to: localhost
# # ansible.builtin.wait_for:
# # timeout: 10
#
# - name: convert obsolete variable ...
# ansible.builtin.set_fact:
# json_exporter_modules: "{{ json_exporter_config | bodsch.prometheus.convert_to_modules(json_exporter_modules) }}"
# json_exporter_config: []

- name: prepare
ansible.builtin.import_tasks: prepare.yml
tags:
Expand Down
Loading

0 comments on commit 7d22f0e

Please sign in to comment.