'How to increment a value on hosts (Ansible)
I have endless kafka servers to configure, their ids must be different from each other. Configuration must be done through jinja templating.
Their broker.id field should start from 0 to infinity if there are infinite number of servers.
# The id of the broker. This must be set to a unique integer for each broker.
broker.id={{ broker_id }}
Expected on the conf files:
server1
broker.id=0
server2
broker.id=1
serverN
broker.id=N-1
EDIT
main.yml
---
- include: install.yml
tags:
- kafka
- install
- include: config.yml
tags:
- kafka
- config
config.yml
---
- name: server properties
template:
src: server.properties
dest: /opt/kafka/config/server.properties
- name: zookeeper properties
template:
src: zookeeper.properties
dest: /opt/kafka/config/zookeeper.properties
defaults/main.yml
---
#server.properties
broker_id: 0
templates/server.properties
.
.
.
############################# Server Basics #############################
# The id of the broker. This must be set to a unique integer for each broker.
broker.id={{ broker_id }}
############################# Socket Server Settings #############################
.
.
.
Ansible is applying same configuration to multiple servers, as normal behavior. But while applying same configuration broker.id must be unique.
{{ 99999999 | random | to_uuid }}
This is working, still i'm curious if it's possible to assign 0 to broker.id and increment +1 on each server?
Solution 1:[1]
Add below
- name: Set Broker ID
set_fact:
broker_id: {{ groups['all'].index(inventory_hostname) }}
followed by other tasks.
Solution 2:[2]
It's possible to create the inventory dynamically in the first play and use it in the second play. For example the playbook below
- hosts: localhost
vars:
no_of_servers: 3
tasks:
- add_host:
name: "srv-{{ item }}"
groups: kafka
id: "{{ my_idx }}"
loop: "{{ range(0, no_of_servers)|list }}"
loop_control:
index_var: my_idx
- hosts: kafka
tasks:
- debug:
msg: "{{ inventory_hostname }} id: {{ id }}"
gives
ok: [srv-0] => {
"msg": "srv-0 id: 0"
}
ok: [srv-1] => {
"msg": "srv-1 id: 1"
}
ok: [srv-2] => {
"msg": "srv-2 id: 2"
}
Solution 3:[3]
Try this, I think it will solve
broker.id={{ (inventory_hostname.split('0')[-1] | int) }}
Solution 4:[4]
May be this helps
- name: Set Broker ID
set_fact:
broker_id: {{ ansible_play_hosts.index(inventory_hostname) }}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Prakash Krishna |
Solution 2 | Vladimir Botka |
Solution 3 | Ricardo Silveira |
Solution 4 | Jijo John |