Dolore
Dolore

Reputation: 21

SaltStack Generate json for prometheus targets

How to add targets to json file with salt, i use file_sd_configs file in prometheus.yml

  - job_name: 'winserver_node'
    file_sd_configs:
    - files:
      - targets.json

targets.json:

[
  {
    "targets": [ "192.168.1.2:9182" ],
    "labels": {
      "env": "dev",
      "job": "devjob",
      "instance": "Test001"
    }
  },
  {
    "targets": [ "192.168.1.3:9182" ],
    "labels": {
      "env": "dev",
      "job": "devjob",
      "instance": "Test002"
    }
  }
]

And wroute some example.sls with pillars, but i wonder how to generate it with file.blockreplace.

#SLS for adding targets for prometheus (nodes)
{% set minion =  salt['pillar.get']('variables:some:instance') %}
{% set minionip = salt ['pillar.get']('variables:some:ip') %}
{% set promenv = salt['pillar.get']('variables:some:promenv') %}
{% set job = salt['pillar.get']('variables:some:devjob') %}
{% set port = salt['pillar.get']('variables:some:exporterport') %}

make-config:
  file.managed:
    - name: /etc/prometheus/targets.json
    - source: salt://prometheus/targets_template.json

main-block:
  file.blockreplace:
    - name: /etc/prometheus/targets.json
    - marker_start: "# START managed zone Target {{ minion }} -DO-NOT-EDIT-"
    - marker_end: "# END managed zone Target {{ minion }} --"
    - backup: '.bak'
    - show_changes: True
    - append_if_not_found: True

Also i have some problems with , and [ ]

Upvotes: 1

Views: 691

Answers (2)

OrangeDog
OrangeDog

Reputation: 38787

You can use file.serialize to write data out into multiple formats, of which JSON is one.

However, you cannot maintain a managed block in a JSON file, simply because the JSON format will not allow it. Comments are not supported, for example.

Upvotes: 0

Dolore
Dolore

Reputation: 21

file_sd_configs may be in yml format. So final result looks like this:

/etc/prometheus/linuxtargets.yml:
  file.touch

main-lin-block:
  file.blockreplace:
    - name: /etc/prometheus/linuxtargets.yml
    - marker_start: "# START managed zone {{ minion }} -DO-NOT-EDIT-"
    - marker_end: "# END managed zone {{ minion }} --"
    - backup: '.bak'
    - show_changes: True
    - append_if_not_found: True

targets-lin-block:
  file.accumulated:
    - filename: /etc/prometheus/linuxtargets.yml
    - name: targets-accum
    - text: |
            - targets:
              - '{{ minionip }}:{{ port }}'
              labels:
                instance: '{{ minion }}'
                job: '{{ job }}'
                env: '{{ promenv  }}'
    - require_in:
      - file: main-lin-block

Upvotes: 1

Related Questions