I need loop over an Ansible role and save the index of the iteration.
My goal is to use the number(which is INDEX in this case) in my-role for each iteration. My-role executes other playbooks and I need the value of the INDEX for each iteration. I want to use that index in another ansible-playbook. So my plan is to set an environment variable to read from the other plaaybook.
This is my code:
- name: my-role
with_sequence: 'start=0 end={{ number_of_users|int }}'
include_role:
name: my-role
vars:
user_name: '{{ user_temp[item|int] }}'
queue_name: '{{ queue_temp[item|int] }}'
lineinfile:
dest: "/etc/environment"
state: present
line: 'export INDEX=[item|int]'
Apparently I cannot do two statements at the same time.
The error message is:
ERROR! conflicting action statements: include_role, lineinfile
Is there a way to set an environment variable while looping over a role?
Is there a way to set an environment variable while looping over a role?
Yes, using the apply:
option of include_role:
- with_sequence: start=0 end=3
include_role:
name: my-role
apply:
environment:
INDEX: '[{{item}}]'
BTW, even if ansible had let you run lineinfile
alongside that role, just putting an entry in /etc/environment
is highly unlikely to automatically expose that environment variable to the role. It would require that every ssh connection made for every task actually source /etc/environment
, which might happen but it's unwise to count on it when ansible offers you an environment:
directive that is explicitly designed to do that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.