Generating Prometheus targets from a CMDB or inventory

Feed Prometheus scrape targets from your CMDB, Ansible inventory or provisioning system using file-based or HTTP service discovery, with labels from inventory fields and a plan for stale entries.

On this page

Generating Prometheus targets from a CMDB or inventory: when teams need it

A hand-maintained prometheus.yml drifts from the CMDB or inventory of record within weeks of the first deployment. Hosts get added to the inventory and never reach a scrape job, decommissioned machines keep being scraped and failing, and nobody can say which list is correct. The fix is to let Prometheus read its targets from files or an HTTP endpoint that your inventory generates, so the source of truth stays in the inventory and Prometheus follows it. Prometheus does this through file-based service discovery (file_sd_configs) or HTTP service discovery (http_sd_configs) rather than requiring every host to be typed into the main configuration.

Prometheus is a pull system. It collects metrics by scraping HTTP endpoints on targets it finds either through service discovery or through static configuration, as described in the Prometheus overview. Static jobs work well when the estate is small and changes rarely, because every new host means a configuration change, a review and a reload. Generated targets fit better when hosts are created and retired often, when several teams own different parts of the inventory, or when the inventory already records roles, environments and owners that should become labels. In those cases the scrape configuration stays fixed and only the target list changes.

Before choosing this route, confirm three things with your platform owners: which system holds the authoritative record of a host, whether that system can export targets in a shape Prometheus accepts, and who is responsible when the export fails. An Ansible inventory, a CMDB export or a provisioning system can each serve as the source, but the export job becomes a production dependency that needs its own monitoring and ownership.

Which discovery method fits which inventory source

This table compares file-based discovery, HTTP discovery and a sync script that writes target files across the factors that decide the choice. Read each row against your inventory system: if the CMDB exposes an API and a team can run a generator job, the options separate quickly. The main takeaway is that how a broken source affects existing targets matters as much as how targets get added.

Decision factorFile-based discoveryHTTP discoverySync script writing target files
Inventory source typeExports from a spreadsheet, Ansible inventory or CMDB dump that someone regeneratesA service or endpoint that returns target lists in Prometheus-compatible JSONAny source with an API, export or query interface, including ones that cannot serve Prometheus formats
Does the CMDB expose an API?Not required, since a file on disk is enoughRequired, and the endpoint must be reachable from the Prometheus serverNot required if the script can read an export, but an API makes it more reliable
Who owns the generatorWhoever produces the file, often a manual or cron-driven processThe team running the HTTP endpoint, which needs its own uptime and access controlA named platform or monitoring team that runs and tests the generator job
Refresh behaviorPrometheus rereads watched files on a schedule, so the file must be updated atomicallyPrometheus polls the endpoint at its configured refresh intervalRefresh depends on the job schedule, so confirm the interval with the team before relying on it
Behavior when the source breaksLast written file stays in place, so existing targets keep being scrapedFailed refresh can drop targets if the endpoint returns an empty or error responseEmpty output can overwrite good files, so the script should validate before replacing them
Stale entry handlingRemoved hosts persist until the file is rewritten without themRemoved hosts disappear when the endpoint stops listing themDepends on script logic, so define how decommissioned hosts are removed
Security exposureOnly file permissions on the Prometheus host matterEndpoint needs authentication, TLS and network restrictionsScript needs read access to inventory and write access to the target directory, so limit both

Setting up CMDB-driven targets step by step

This sequence turns inventory records into a Prometheus scrape configuration that picks up new hosts, applies consistent labels, and drops retired hosts without manual edits to prometheus.yml.

  1. Define the inventory to label mapping

    Before writing any code, list the inventory fields you want to become Prometheus labels and map each one to a label name, such as environment, role, and owner. Decide which fields are stable identifiers and which change often, since high-churn values such as ticket numbers or free-text notes should stay out of labels. Agree the mapping with the team that owns the CMDB or Ansible inventory, because they will change the source data. Done when you have a written table with one row per label, its source field, its allowed values, and a named owner. Each label value multiplies series, so keep the label set small and bounded.

  2. Build the generator or endpoint

    Write a small script or service that reads the inventory and emits targets in the format Prometheus expects. For file-based discovery, the output is a JSON or YAML list of objects with a targets array and a labels map. For HTTP discovery, the endpoint returns the same structure over HTTP. Run the generator against a copy of the inventory and inspect the output by hand for missing fields, duplicate addresses, and unexpected characters. Done when the generated file matches your mapping table for a sample of at least a few known hosts, and the generator exits with a non-zero status on malformed input instead of writing an empty file.

  3. Write target files with correct permissions

    Write the generated file to a directory the Prometheus process can read, owned by the account that runs the generator and readable by the account that runs Prometheus. Write to a temporary file and rename it into place so Prometheus never reads a partial file. Confirm the ownership and mode on the target host, and confirm that the Prometheus container or service can see the path if it runs in Docker or a systemd sandbox. Done when a read as the Prometheus user succeeds and the file parses as valid JSON or YAML. Schedule the generator with cron or a systemd timer, and record the schedule so the team knows how stale the file can become.

  4. Configure the scrape job

    Add a scrape job to prometheus.yml that points at the generated files with file_sd_configs, or at the endpoint with http_sd_configs. Set the files pattern to the full path and add a relabel rule only if you need to change how the discovered address is used. Keep the job name and label names identical to the mapping table from the first step. The file_sd_configs block reloads when the watched files change, so you do not need to reload Prometheus after each generator run. Done when the configuration file is saved and the job name appears in the list you expect. Store the file in version control with the rest of your Prometheus configuration.

  5. Validate the configuration with promtool

    Run promtool check config against the main configuration file before loading it. The check catches YAML errors, unknown keys, and invalid regular expressions in relabel rules, and it reports the file paths it reads. Run the same check in your CI pipeline so a change that breaks the configuration is caught before it reaches the server. Done when promtool reports success with no errors. Note that promtool validates syntax and structure but cannot confirm that the discovered targets are reachable, so the next checks still matter.

  6. Reload Prometheus and confirm the targets page

    Reload Prometheus so the new scrape job takes effect. A reload can use SIGHUP to the process, or the HTTP lifecycle endpoint, but the lifecycle endpoint only works when Prometheus was started with the --web.enable-lifecycle flag, which is off by default. Check the flags on your running instance before relying on the endpoint. Then open the targets page in the web UI, or query the targets API, and compare the list with your inventory for the expected count, labels, and health status. Done when every expected host appears with the labels from your mapping, and any target in a down state has a known cause.

  7. Check stale entries and removed hosts

    Test what happens when an inventory record is removed or a host is retired. Remove one test host from the source data, run the generator, and confirm the target disappears from the targets page after the file is rewritten. Also confirm what happens if the generator fails: the last good file should stay in place and an alert or log entry should show the failure, rather than an empty file silently removing every target. Document the expected behavior for stale data and who receives the alert. Done when a removed test host leaves the targets page and a failed generator run leaves the previous targets intact.

  8. Document the workflow and handover

    Write a short runbook that names the inventory owner, the generator owner, the file path, the schedule, the promtool step in CI, the reload method in use, and the check that confirms a successful change. Include the rollback step: restore the last good file and confirm the targets page again. Record which lifecycle or admin flags are enabled on the server and why, because those settings affect who can trigger reloads. Done when another engineer can follow the runbook to add a host, retire a host, and recover from a failed generator run without asking the original author.

Mapping inventory fields to labels without cardinality surprises

A CMDB usually holds the richest set of fields, and most of them are unsafe as labels. Stable classification fields such as environment, business service, data classification and owning team change slowly and have a small set of values, so they suit labels well. Fields that describe a single configuration item, such as serial numbers, asset tags, IP addresses or free-text notes, create a new series for every value and should stay in the inventory or move to a separate lookup. Ask your CMDB owner which fields are enforced picklists and which are free text, because free text is the usual source of surprises.

  • Promote picklist fields: Environment, service tier and region map well to labels when the CMDB enforces a fixed list.
  • Keep identifiers out: Serial numbers, asset tags and MAC addresses identify single machines and multiply series without adding a useful grouping.
  • Never copy notes or descriptions: Free-text fields change with every edit and can contain arbitrary characters.
  • Drop timestamps: Fields such as last-audited or created-at change over time and produce new series on each change.
  • Filter at export: Have the export job select only the approved fields so a new CMDB column cannot reach Prometheus by default.

Before go-live, check the distinct value count of each candidate field in a sample export and confirm the list with the CMDB owner.

Handling stale entries when hosts are retired

Generated target files are only as current as the inventory and the generator behind them. The risks below share one root cause: the file on disk drifts from the hosts that actually exist, and Prometheus will faithfully scrape or silently skip whatever the file says. Each card names the signal to watch and the control to put in place before the first retirement happens.

Decommissioned hosts still scraped

A host removed from the CMDB but left in the target file keeps producing scrape failures, and its up series drops to 0 while alerts fire on a machine nobody owns. Check whether the generator deletes entries for retired records or only adds new ones. Set a rule that a retirement ticket closed in the CMDB removes the host from the generated file on the next run, and review the up == 0 list for hosts with no active owner.

Generator failures that empty target files

If the generator cannot reach the inventory API or receives an empty response, it may write a file with no targets, and every job built on that file goes quiet at once. The signal is a sudden drop in the count of active series per job, not a single failing target. Have the generator refuse to overwrite the live file when the new output is empty or sharply smaller than the last run, and keep the previous file as a fallback.

Duplicate targets from two sources

When a host appears in both the CMDB export and an Ansible inventory, or under two names, Prometheus scrapes it twice and series with identical labels can collide or double-count in dashboards. Look for repeated instance values across jobs. Choose one system of record per label set, and have the generator de-duplicate on the target address before writing the file.

Temporary inventory gaps causing alert noise

A host briefly missing from inventory during a sync, reimage or migration can drop out of the target file, and alerts that depend on its series may resolve and refire. The signal is a burst of alert state changes that line up with generator runs. Treat missing entries as a reason to hold them for a grace period before removing them, and test alert rules against that gap before rollout.

Silent loss of missing targets

A target removed from the file stops producing series without any failed scrape, so no target-down alert fires and the gap is easy to miss. Compare the target list Prometheus reports on its targets page with the list the inventory expects, and alert on the difference. Keep a count of expected targets per job as an alerting input, not only a dashboard number.

Unreviewed changes to label values

Inventory fields such as environment, owner or service tier become labels, and a silent edit in the CMDB can rename a label value, split a series or move alerts to the wrong team. Check changes to label values in the generator's output diff before they reach the server. Require review for label-affecting fields, and record the generator version and inventory snapshot used for each file so a change can be traced.

How inventory data reaches Prometheus scrapes

The flow starts in the inventory network, where the CMDB or Ansible inventory is the source of truth. A generator reads it and writes either a file-based target list or serves an HTTP endpoint for http_sd. The trust boundary sits where Prometheus pulls that output across into the monitoring network. Check what crosses that boundary, who can write the target file or endpoint, and how stale entries are removed before alerts fire on hosts that no longer exist.

Inventory data moves through a generator or endpoint into Prometheus scrape jobs across a trust boundary.

Limits to confirm in your environment before you rely on generated targets

Generated targets are only as reliable as the inventory feeding them and the Prometheus release running them. The cards below cover the questions to settle with your platform team before a CMDB or inventory becomes the source of truth for scrape configuration.

Discovery keys and refresh defaults

File-based and HTTP service discovery options, and how often Prometheus re-reads a target file or polls an endpoint, can differ between versions. Confirm the exact keys your target version accepts and the refresh behavior it uses, then test a change end to end in a non-production instance. Do not assume a default you read in an older guide still applies.

Prometheus overview

Inventory API and required fields

Generated targets need the inventory to expose the hostname or address, port, environment, owner and role fields you plan to turn into labels. Confirm whether your CMDB or Ansible inventory offers an API or export that returns those fields reliably, and who owns the data quality of each one. Missing or inconsistent fields become missing or inconsistent labels.

Failure modes and tests

Decide what Prometheus should do when the inventory is unreachable, returns an empty list, or returns a malformed file. Test each case with a deliberate outage and a bad export, and confirm whether targets disappear, persist or fail the refresh. Record the expected behavior so on-call engineers know whether a drop in targets is an inventory problem or a monitoring gap.

Single-node storage

Prometheus local storage is not clustered or replicated and should be managed like any other single-node database. Target discovery problems and storage problems look similar on dashboards, so keep them separate in your runbooks. Losing a target from the file or API is an inventory or configuration issue, not a reason to assume data loss, and the storage docs should guide your backup plan.

Prometheus storage docs

Supported release line

Confirm that the Prometheus release line you deploy is still receiving fixes before you build discovery on it. Minor releases generally stop receiving bug fixes after six weeks, while long-term support lines receive fixes for one year. Check the current release-cycle page at the time of rollout, since the supported lines change over time.

Minor release fix window
6 weeks
Release cycle page

Questions buyers ask about CMDB-driven Prometheus targets

How much effort does a CMDB-driven target integration take?

The effort depends mostly on how many inventory sources feed Prometheus, how much label design the inventory needs, and how reliable the generator script or service is. One source with clean fields and a stable export is a small job. Several sources with inconsistent hostnames, duplicate records and fields that do not map to useful labels take much longer, because each mismatch needs a rule and a test. The generator is the part that needs the most care: it must handle failed API calls, partial exports and empty results without wiping the target files that Prometheus depends on. Ask any partner to break the estimate into inventory discovery, label mapping, generator build, validation and handover.

Can our team build a CMDB-to-Prometheus integration internally?

Yes, if the team already runs Prometheus, can write and test a small script or service, and has an owner for the inventory data. The file-based and HTTP service discovery mechanisms are documented and do not require special tooling. The harder parts are usually organizational: agreeing which inventory fields become labels, deciding what happens to decommissioned hosts, and keeping the generator running after the original author moves on. Teams that lack a Prometheus operator or an engineer comfortable with the inventory's API often find the integration stalls at label design. A partner can cover that gap, or review your design before you build.

What does the integration need from our team?

The work needs three things from your side. First, an inventory owner who can explain which fields are authoritative, how often records change, and which hosts should be monitored. Second, read access to the CMDB, Ansible inventory or provisioning API, using a service account with the narrowest permissions that can list the required records. Third, a test environment with a Prometheus instance and a non-production copy or filtered export of the inventory, so changes to the generator can be checked before they reach production targets. Expect your team to review label names and approve the cutover, since those decisions affect dashboards and alert rules downstream.

How long does the work take?

No duration has been established for this work, and it is set by scope rather than by a fixed template. The main variables are the number of inventory sources, how much cleanup the inventory data needs before it can drive labels, whether file-based or HTTP service discovery is used, and how many environments must be covered. Ask a partner for a written scope and timeline before work starts, and check that it lists the inventory sources, the label model, the validation steps and the cutover plan. Your inventory owners' availability often determines the schedule as much as the engineering work does.

What keeps running after go-live?

Several things recur after the integration is live. The generator needs maintenance when the inventory API changes, when a new source is added, or when a Python or runtime dependency needs updating. Label schemas need periodic review, because teams rename fields in the CMDB and dashboards and alert rules that depend on old labels can quietly break. Prometheus itself needs upgrades on a planned cadence. The release cycle page notes that a minor release generally stops receiving bug fixes six weeks after it starts, and long-term support lines receive fixes for one year, so the generator and the Prometheus version should be reviewed together. Stale-entry handling also needs ongoing checks, since decommissioned hosts that remain in the inventory keep producing targets.

When is a managed or Kubernetes-native discovery method a better fit?

A CMDB-generated target file makes sense when your authoritative list of hosts lives outside the platform, such as in an inventory system that finance, security or change management already audits. If your workloads run on Kubernetes, the Kubernetes service discovery support in Prometheus usually discovers pods and services directly from the cluster API, which removes the generator from the path. Cloud providers offer their own discovery mechanisms for instances that are created and destroyed automatically. If the inventory is not your source of truth for running services, a generator adds a sync delay and another component to maintain. Confirm which discovery method matches your environment before building anything, and consider a hybrid approach when some hosts are in Kubernetes and others are not.

What are the main risks of feeding Prometheus from an inventory?

The most common risk is silent loss of coverage. If the generator writes an empty or partial target file after an API failure, Prometheus may drop targets and alerts that depend on them can stop firing without any error on screen. Prometheus also values reliability over precision, so the team should set up monitoring of the generator and of target counts, not just of the hosts themselves. A second risk is label drift, where inventory fields change meaning and dashboards or alert rules are left pointing at the wrong data. Finally, the inventory credentials become a sensitive asset, because anyone who can read the generator's configuration can often read host lists. Store those credentials in a secrets manager and restrict access to the generator's host.

How DeployOpen scopes and delivers CMDB-driven Prometheus targets

DeployOpen plans and implements self-hosted Prometheus inside your own infrastructure, and the target pipeline from your CMDB, Ansible inventory or provisioning system is scoped as its own deliverable. Engagements are usually fixed-scope, which means the systems in scope, the inventory sources, the label model, the generated file or HTTP endpoint formats, the refresh behavior and the handling of stale entries are agreed in writing before work starts, together with the deliverables and timelines. Nothing about the work is hidden in a later change order if the scope is written carefully at the start.

The written scope usually covers the label model that inventory fields map to, such as environment, owner, site and role, and the rules that decide which hosts become scrape targets at all. It also covers the configuration as code that produces the target files, the Prometheus settings that read them, and the tests that show what happens when the CMDB is unreachable, returns partial data or drops a host. DeployOpen documents this model and configuration so your team can review changes and run them after handover. Ask any partner to show you exactly which of these items appear in its scope document and which are left to you.

Ongoing support is available as a retainer for label model changes, Prometheus version upgrades, new inventory sources and periodic failure testing. DeployOpen does not publish prices, so a quote follows from the written scope. To compare offers, ask each provider for the list of inventory sources and environments covered, the number of label rules and failure cases tested, the documentation delivered, and what is included after go-live. Those answers determine the cost far more than the number of hosts alone.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.