How to log inventory_hostname to a file on the remote using a Playbook

ansibleansible-playbook

I'm trying to write the inventory hostname to a remote file for later processing (eventually a remote fact file). The host below has the physical hostname calvin.mydomain however the controller connects to it using the inventory hostname (different DNS) calvin.test.mydomain so I can't just use the -m setup fact variables which only gather info from the perspective of the remote (AFAIK).

I thought I could do this by exporting an environment variable to the remote and then writing it to a file but that just produces the literal word inventory_hostname.

How can I write hostvars[inventory_hostname] or {{inventory_hostname}} to a file in /etc/ansible/facts.d/ in the remote?

sudo ansible-playbook ./playbooks/hostname.yml -k -u root -i calvin.test.mydomain,
TASK [echo the LAN_HOSTNAME environment var] *******...
changed: [calvin.my.testing.dom]

this is my playbook

---
- hosts: all
  tasks:
      - name: "echo the LAN hostname into a file on the remote"
        shell: "echo $LAN_HOSTNAME > /tmp/hostname.ans"
        environment:
            LAN_HOSTNAME: inventory_hostname

Best Answer

needed to use this (changed to copy as suggested by @Michael Hampton):

---
- hosts: all
  tasks:
   - name: "Create custom fact directory"
     file:
         path: "/etc/ansible/facts.d"
         state: "directory"

   - name: "Insert custom fact file"
     copy:
         content: "#!/bin/bash\necho {\\\"ansible_LAN_hostname\\\" : \\\"{{ inventory_hostname }}\\\"}"
         dest: /etc/ansible/facts.d/lan_hostname.fact
         owner: root
         group: sysadmin
         mode: 0775