Delegate to localhost does not change inventory_hostname, if it did it would break a lot of code out there.
And I can prove it with this code that mimic you codes behavior.
$ more test.yml
---
- hosts: a1,a2
gather_facts: no
become: no
vars:
myvar:
- value1
- value2
- value3
tasks:
- lineinfile:
path: /tmp/test
line: "{{ inventory_hostname }} {{ item }}"
insertafter: EOF
create: true
delegate_to: localhost
when: item == "value2"
with_items: "{{ myvar }}"
And by running it I get
$ ansible-playbook test.yml; echo "Content of /tmp/test:"; cat /tmp/test
PLAY [a1,a2] ***************************************************************
TASK [lineinfile] **********************************************************
skipping: [a1] => (item=value1)
skipping: [a2] => (item=value1)
changed: [a1 -> localhost] => (item=value2)
skipping: [a1] => (item=value3)
changed: [a2 -> localhost] => (item=value2)
skipping: [a2] => (item=value3)
PLAY RECAP *****************************************************************
a1 : ok=1 changed=1 unreachable=0 failed=0
a2 : ok=1 changed=1 unreachable=0 failed=0
Content of /tmp/test:
a1 value2
a2 value2
--
Kai Stian Olstad