๐Ÿ“— Ansible playbooks and roles for building an idempotent, interconnected and scalable infrastructure
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
ansible-playbooks/roles/prometheus/tasks/add_target.yml

78 lines
2.8 KiB

- name: check if target is an object
fail:
msg: target must be an object
when: target is not mapping
- name: check if target parameters are defined
fail:
msg: some target parameters are invalid or not defined
when: target.name is not string
- name: fail if prometheus is not present
debug:
msg: prometheus host is missing, will not add target
when: services.prometheus is not defined or services.prometheus.hostname is not defined
- block:
- name: slurp prometheus config
slurp:
path: "{{ hostvars[services.prometheus.hostname]['prometheus_conf_file'] | d(prometheus_conf_file) }}"
register: slurped_config_file
delegate_to: "{{ services.prometheus.hostname }}"
- name: parse config file
set_fact:
pm_config_file: "{{ slurped_config_file.content | b64decode | from_yaml }}"
- name: construct scrape target config snippet
set_fact:
pm_target:
job_name: "{{ target.name if (target.exact_name | d(false) == true) else (target.name ~ '-' ~ inventory_hostname ~ '-' ~ ansible_host) }}"
scrape_interval: "{{ target.scrape_interval | d(None) }}"
scrape_timeout: "{{ target.scrape_timeout | d(None) }}"
metrics_path: "{{ target.url | d('/metrics') }}"
scheme: "{{ target.scheme | d('http') }}"
static_configs:
- targets:
- "{% if target.use_ip | d(false) == true -%}\
{{ target.ip | d(ansible_host) }}\
{% else -%}\
{{ (target.hostname | d(host_name)) ~ '.' ~ (target.tld | d(host_tld)) }}\
{% endif -%}{{ (':' ~ target.port) if target.port is defined else '' }}"
- name: finalize building scrape snippet
set_fact:
pm_target_final: "{{ pm_target | combine(target.extra_params | d({}), recursive=true) | dict2items | rejectattr('value', 'equalto', None) | list | items2dict }}"
- name: output scrape target config
debug:
msg: "{{ pm_target_final }}"
- name: update prometheus config
blockinfile:
path: "{{ hostvars[services.prometheus.hostname]['prometheus_conf_file'] | d(prometheus_conf_file) }}"
block: "{{ [pm_target_final] | to_nice_yaml(indent=2, width=512) | indent(width=2, first=true) }}"
insertafter: "--- scrape config begin ---"
marker: " # target: {mark}"
marker_begin: "{{ pm_target_final.job_name }} begin"
marker_end: "{{ pm_target_final.job_name }} end"
delegate_to: "{{ services.prometheus.hostname }}"
register: result
- name: restart prometheus if its config was changed
service:
name: prometheus
state: restarted
delegate_to: "{{ services.prometheus.hostname }}"
when: result.changed
when: services.prometheus is defined and services.prometheus.hostname is defined