Use lineinfile to fill ansible inventory file -
i have trivial task fill particular ansible inventory file new deployed vms names under roles. here playbook:
- hosts: 127.0.0.1 tasks: - name: add host inventory file lineinfile: dest: "{{inv_path}}" regexp: '^\[{{role}}\]' insertafter: '^#\[{{role}}\]' line: "{{new_host}}"
instead of adding new line after [role], ansible replace string hostname. aim naturally insert after it. if there no matched role should skip add new line.
how achieve this? thanks!
[role]
getting replaced because regexp
parameter regular expression ansible replace line
parameter. move value insertafter
, rid of regexp
.
as other requirement need task check if [role]
exists first. lineinfile task evaluate result of checker task determine if should run.
- name: check if role in inventory file shell: grep [{{ role }}] {{ inv_path }} ignore_errors: true register: check_inv - name: add host inventory file lineinfile: dest: "{{ inv_path }}" insertafter: '^\[{{role}}\]$' line: "{{new_host}}" when: check_inv.rc == 0
Comments
Post a Comment