Reputation: 305
Is it possible to define different sequential value for different hosts in the same group?
I have a job with multiple tasks that loops for every hosts in the host group.
For example: my_host group contains 3 hosts A, B, C and 5 tasks
The 5 tasks will run 3 times for each hosts A, B, C
However in 1 variable of the 5 tasks that I have, I want to pass a sequential value for each hosts
So variable 'sequential_var' will have value 1 in host A, value 2 in host B, and value 3 in host C
I have tried
- hosts: my_host
serial: 1
tasks:
- name: task1
set_fact:
sequential_var: {{ item }}
with_sequence: start=1 end=3
the value ended up being 3 for all of the host when i actually want 1 for A, 2 for B and 3 for C
is there anyway for me to achieve what i actually want?
Upvotes: 1
Views: 413
Reputation: 68074
Q: "The variable 'sequential_var' will have value 1 in host A, value 2 in host B, and value 3 in host C"
A: Given the inventory
shell> cat hosts
[my_host]
A
B
C
Get the index of the host in the group, e.g.
- hosts: my_host
gather_facts: false
vars:
sequential_var: "{{ groups.my_host.index(inventory_hostname) + 1 }}"
tasks:
- debug:
var: sequential_var
gives
ok: [A] =>
sequential_var: '1'
ok: [B] =>
sequential_var: '2'
ok: [C] =>
sequential_var: '3'
The directive serial has no effect on the variable sequential_var. The value of sequential_var will be the index of the host in the group as ordered in the inventory.
Upvotes: 1
Reputation: 841
You are trying to assign variable to hosts.
From ansible documentation
You can store variable values that relate to a specific host or group in inventory. To start with, you may add variables directly to the hosts and groups in your main inventory file. As you add more and more managed nodes to your Ansible inventory, however, you will likely want to store variables in separate host and group variable files
You can do this while you configure your ansible hosts.
myhosts:
hosts:
A:
id: 1
B:
id: 2
Upvotes: 0