How does ansible.builtin.fetch store a file on the control node, and why does dest: "files/keys/{{ user }}.pub" not create a file with that name?
fetch treats dest as a directory and appends <hostname>/<full source path>, so one file per host can't collide; to get exactly files/keys/<user>.pub, add flat: true.
* Without flat, every host gets its own subtree; flat: true writes exactly to dest. *
fetch copies in the reverse direction to copy: from the managed hosts to the control node. A typical use is collecting a public SSH key from a reference host before distributing it to others:
- name: Retrieve SSH key from reference host
ansible.builtin.fetch:
src: "/home/{{ user }}/.ssh/id_rsa.pub"
dest: "files/keys/{{ user }}.pub"
flat: true
Because fetch usually runs against many hosts, its default layout is dest/<inventory hostname>/<src path>. Without flat, the task above would create a directory files/keys/alice.pub/ containing host1/home/alice/.ssh/id_rsa.pub, which surprises everyone the first time. With flat: true, the file is written to dest as given; then make sure the name is unique per host, or the hosts overwrite each other.
(Also make sure every quoted value is closed: src: "/home/{{ user }}/.ssh/id_rsa.pub without the closing quote is a YAML syntax error.)
Go deeper:
ansible.builtin.fetch: flat (official docs) โ the default
hostname/pathlayout and howflatchanges it.