Inventory file (inventories/test/environments/tmp6.yml):
test:
children:
environments:
children:
tmp6:
tmp6:
vars:
ansible_user: superuser
ansible_password: superuser
ansible_become_password: "{{ ansible_password }}"
children:
infra:
hosts:
host_5:
ansible_host: 192.168.1.72
host_6:
ansible_host: 192.168.1.83
tools:
hosts:
host_7:
ansible_host: 192.168.1.239
host_8:
ansible_host: 192.168.1.46
General playbook.yml
:
- hosts: environments
roles:
- role: host-configuration
- role: host-users
- role: node-exporter
post_tasks:
- ansible.builtin.copy:
content: |
- target:
- {{ ansible_host }}:9100
labels:
environment_name: {{ inventory_file | ansible.builtin.basename | ansible.builtin.regex_replace('.yml$', '') }}
environment_type: {{ inventory_file | ansible.builtin.dirname | ansible.builtin.dirname | ansible.builtin.basename }}
dest: "./{{ inventory_file | ansible.builtin.basename }}"
delegate_to: localhost
After successfully installing the node_exporter on the nodes, need to create a common configuration file for the environment:
- target:
- 192.168.1.72:9100
- 192.168.1.83:9100
- 192.168.1.239:9100
- 192.168.1.46:9100
labels:
environment_name: tmp6
environment_type: test
The main problem in formation the list of targets.
If create such a template:
- target:
- {{ ansible_host }}:9100
labels:
environment_name: {{ inventory_file | ansible.builtin.basename | ansible.builtin.regex_replace('.yml$', '') }}
environment_type: {{ inventory_file | ansible.builtin.dirname | ansible.builtin.dirname | ansible.builtin.basename }}
value of the variable ansible_host
always changes. Therefore it is not a solution.
How to create a dynamic host list in a playbook?
P.S.: Playbook can be applied to multiple environments:
ansible-playbook playbook.yml -i inventories/test -l tmp1,tmp3,tmp6
General task:
- install the node_exporter on the nodes of group "environments"
- create a common configuration files on the localhost
- copy the configuration files to the host "prometheus"
Ansible doesn't know anything about your "environments". If you want to use that information in your playbooks, you'll need to add it to your inventory. For example, we can add
environment_type
andenvironment_name
variables like this:Given the above inventory file, we can write a playbook like this:
If we run:
We get:
If we limit by environment, like this:
We get:
And finally, if we limit to individual hosts, like this:
We get:
The problem can be solved with intermediate temporary files.
Final playbook:
UPDATE
The problem can be solved without intermediate temporary files.
Final playbook: