Taavi Ansper
Taavi Ansper

Reputation: 163

Ansible lineinfile append

I have a hosts inventory file. That has

url.example.com hostnames='["hostname1.example.com", "hostname2.example.com"]'

Im trying to loop over it to add all the hostnames to /etc/hosts file

I am trying to use lineinfile, but how can I get it to append all of the hostnames to one specific line

line: "{{ ansible_default_ipv4.address }} {{ inventory_hostname }} {{ inventory_hostname_short}}" + append item here
with_items: "{{ hostnames }}"
state: present

How can i append all the items in the end of the line.

Upvotes: 2

Views: 657

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68394

The iteration is not needed, I think. Is this what you're looking for?

  line: "{{ ansible_default_ipv4.address }}
         {{ inventory_hostname }}
         {{ inventory_hostname_short}}
         {{ hostnames|join(' ') }}"

For example, given the file

shell> cat hosts
10.1.0.27 localhost localhost

The playbook

shell> cat playbook.yml
- hosts: localhost
  vars:
    hostnames: [hostname1.example.com, hostname2.example.com]
  tasks:
    - lineinfile:
        path: hosts
        regex: '^{{ ansible_default_ipv4.address }}\s+(.*)$'
        line: "{{ ansible_default_ipv4.address }}
               {{ inventory_hostname }}
               {{ inventory_hostname_short}}
               {{ hostnames|join(' ') }}"

works as expected

shell> ansible-playbook playbook.yml -CD

TASK [lineinfile] ***************************************************************
--- before: hosts (content)
+++ after: hosts (content)
@@ -1 +1 @@
-10.1.0.27 localhost localhost
+10.1.0.27 localhost localhost hostname1.example.com hostname2.example.com

changed: [localhost]

Upvotes: 1

Related Questions