Update inventory file

52 views
Skip to first unread message

Edgardo Vega

unread,
Jul 24, 2015, 11:20:14 AM7/24/15
to Ansible Project
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===
---
- name: create instances
  hosts: all
  gather_facts: no
  connection: local
  sudo: no
  tasks:
    - name: "create instance and assign floating-ip (if available)"
      os_server:
       state: present
       auth:
         auth_url: http://10.10.81.227:5000/v2.0
         username: "{{openstack_username | mandatory }}"
         password: "{{openstack_password | mandatory }}"
         project_name: cups
       name: "{{ inventory_hostname | mandatory }}"
       image: "{{ openstack_image | mandatory }}"
       key_name:  "{{ openstack_key_name | mandatory }}"
       flavor: "{{ openstack_flavor | mandatory }}"
      register: result
      
    - debug: var=result
    
    - debug: var=inventory_hostname

    
    - lineinfile: backrefs=yes state=present  dest="{{inventory_dir}}/test" regexp='{{inventory_hostname}}\s' line='{{inventory_hostname}} ansible_ssh_host={{result.openstack.accessIPv4}}'
      
===inventory file====
[tomcat]
tomcat

[jenkins]
jenkins

[downloads]
downloads

[project:children]
tomcat
jenkins
downloads

[cups:vars]
ansible_ssh_user=centos



rmullinnix

unread,
Jul 24, 2015, 6:21:19 PM7/24/15
to Ansible Project, edgard...@gmail.com
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
Reply all
Reply to author
Forward
0 new messages