# Ansible loop with include\_tasks preserves variables from other iterations

**URL:** <https://forum.ansible.com/t/ansible-loop-with-include-tasks-preserves-variables-from-other-iterations/10829>\
**Category:** Get Help\
**Created:** [November 11, 2024, 3:20pm UTC](https://forum.ansible.com/t/ansible-loop-with-include-tasks-preserves-variables-from-other-iterations/10829 "2024-11-11T15:20:16Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![pieterjanv](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/pieterjanv/32/5401_2.png) [@pieterjanv](https://forum.ansible.com/u/pieterjanv)\
**Post date:** [November 13, 2024, 12:29pm UTC](https://forum.ansible.com/t/ansible-loop-with-include-tasks-preserves-variables-from-other-iterations/10829/7 "2024-11-13T12:29:29Z")

</div>

I take it you want facts defined in `network_port_channel.yml` to be local to that file. If that file were a role it would be a special case of a problem I attempted to solve very recently (see [my post on the topic](http://forum.ansible.com/t/a-simple-approach-to-locally-scoped-facts-asking-for-feedback/10797/6)), so I have a suggestion.

While you can refactor to a role and use my collection, I wouldn’t bet on it being production ready. Instead, since I believe you are in control of all the code, you can set a dictionary as a fact at the start of each iteration, and set any local facts on that dictionary fact.

```yaml
--- # network_port_channel.yml
- name: reset the fact to serve as a local namespace
  ansible.builtin.set_fact:
    local: {}
- name: set `my_fact` key on `local`
  ansible.builtin.set_fact:
    local: "{{ local | combine({ 'my_fact': my_value }) }}"
- name: use the local fact
  ansible.builtin.debug:
    var: local.my_fact
- ...

```

---

_[View the full topic](https://forum.ansible.com/t/ansible-loop-with-include-tasks-preserves-variables-from-other-iterations/10829)._
