Update inventory file

I have a playbook with is creating vms and then i want to add the ip address to the inventory file to when it comes time to provision i can just call the updated inventory file. lineinfile will only add to the found lines at the end of the file. replace will update all the matches. What is the recommended way to do this?

===playbook===

One way is to create a new file with the host name and the ip address, then use this to update the hosts file as opposed to updating it in place. You can use the post_tasks: to run the update at the end of the playbook.

You can do this with sed by creating a sed script file with lines of – s/hostname/hostname ansible_ssh_host=ipaddress/g. You can use lineinfile - which will add to the EOF. call it hosts.update

Then you would have a task that would update the hosts file
post_tasks:

  • name: update hosts file with ip address
    shell: sed -i -f hosts.update hosts

I’m sure there is probably a better way to do this