include lines from a text file inside a .j2 file

27 views
Skip to first unread message

Dalton Porter

unread,
May 23, 2017, 5:09:58 PM5/23/17
to Ansible Project
I have a list of items in a text file that need to go into a specific location in the output file.

The text file is one item per line:
user1
user2
...

The output file looks like
Section1:

Section2:
user=user1, task=shuffle
user=user2, task=shuffle
...
Section3:
----------------
I'm using ansible templates to do this.
- name: configure users
  template: src=roles/sys/templates/users.j2 dest=/opt/users.dat backup=yes



I need the users to go in section 2.  I've tried things like this but I can't find what works yet.

In the j2 file:
Section1: 
Section2:
{% for name in item %}
user= {{name}} , task=shuffle
{% endfor %}
Section3:

How should I read in the users from the file?  Store the file data in what?
How do I then feed that to the template so that the for loop works?

 





Dick Visser

unread,
May 23, 2017, 5:37:30 PM5/23/17
to ansible...@googlegroups.com
You want to use a lookup:



vars:
users: "{{ lookup('file', '/home/dalton/users.txt') }}"

tasks:
- name: Template out
template:
src: roles/sys/templates/users.j2
dest: /opt/users.dat
backup: yes

Your template would then look like:

Section1:
Section2:
{% for name in users.splitlines() %}
user= {{ name }}, task=shuffle
{% endfor %}
Section3:


Dick

On 23 May 2017 at 21:24, 'Dalton Porter' via Ansible Project
> --
> You received this message because you are subscribed to the Google Groups
> "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ansible-proje...@googlegroups.com.
> To post to this group, send email to ansible...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/8c148bfb-3e0e-46e5-b0ab-08768d51f7bd%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
Dick Visser
Sr. System & Network Engineer
GÉANT

Want to join us? We're hiring: https://www.geant.org/jobs
Reply all
Reply to author
Forward
0 new messages