Ansible: 'item' is undefined
You need to take care of indention. delegate_to
and with_items
are part of the task, not of the docker module.
- name: Run app container
docker:
name: "{{artifact_id}}"
insecure_registry: true
image: "{{image}}:{{version}}"
pull: always
state: reloaded
ports:
- "{{port_mapping}}"
delegate_to: '{{item}}'
with_items: "{{groups['test']}}"
Though I'm not sure your delegation will work here. What is the background why you need to delegate it in the first place? The normal way would be to apply the play to the hosts of the group test
. I guess you're instead running the play against localhost?
Another unrelated thing: I experienced issues with the docker module when pull: always
used together with state: reloaded
. Unlike docker-compose, the docker module will always restart the container no matter if there was an updated image pulled or not.
- hosts: localhost
tasks:
- download nexus
- build image
- upload to registry
- ...
- hosts: test
tasks:
- docker: ...
Héctor
Dev by trade, Ops for necessity. Freelance software engineer, focused on backend development and cloud native architectures.
Updated on February 09, 2020Comments
-
Héctor over 4 years
I'm trying to use
with_items
withdelegate_to
to run a Docker container in several hosts. I have a grouptest
in/etc/ansible/hosts
:[test] my_machine1 my_machine2
And this task:
- name: Run app container docker: name: "{{artifact_id}}" insecure_registry: true image: "{{image}}:{{version}}" pull: always state: reloaded ports: - "{{port_mapping}}" delegate_to: '{{item}}' with_items: - "{{groups['test']}}"
But when I run it, I get this error:
{"failed": true, "msg": "ERROR! 'item' is undefined"}
What am I doing wrong?
Thanks in advance
-
Michael over 8 yearsYour formatting seems off. Could you format the question yaml just to avoid confusion?
-
Héctor over 8 yearsLOL, It was the problem! delegate_to and with_items are not docker module's properties but task itself ones -.-" Thanks.
-
-
Héctor over 8 yearsThank you very much. It solved the problem. Yes, I'm running in localhost several actions (download the image from nexus and build it) and the last one, that is run the container, must be executed in
test
machines. Should I do it another way? Thank you. -
udondan over 8 yearsYou could add a 2nd play. The 1st play builds your image and (I guess uploads it to a private registry). The 2nd play runs the docker module. I added a dummy example playbook above. But I see how the delegation makes sense for you. If the delegation indeed works, go for it if you prefer it that way.
-
Héctor over 8 yearsPerfect. Thank you again.