Arani
Arani

Reputation: 182

Ansible loop through file

I have a file with user name and few other details (each line is comma separated) as below.

user1,group1,sudoer-y,<public key> 
user2,group1,sudoer-n,<public key>

I need to loop through this file in my playbook and update the sudoers file for each line (depending on whether the flag is y or n).

As a first step I want to print out each column separately. Here is the command I am using:

- name: add to sudoers
  shell: cat /tmp/aws_user_detail.tmp
  register: res

- debug: var=res
  with_items: [ "{{ res.stdout.split(',')[0] }}" ]

But this really prints out the whole file in yml format. Is there an easier way of doing this?

Thanks Arani

Upvotes: 0

Views: 2503

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68339

Iterate over lines and split items:

- name: get file lines
  shell: cat /tmp/aws_user_detail.tmp
  register: res

- debug: msg="user={{ item.split(',')[0] }}"
  when: item.split(',')[2] == "sudoer-y"
  with_items: "{{ res.stdout_lines }}"

Or grep names only, if you need just user names with sudoer flag:

- name: get users with flag
  shell: grep 'sudoer-y' /tmp/aws_user_detail.tmp | cut -d',' -f1
  register: res

- debug: msg="user={{ item }}"
  with_items: "{{ res.stdout_lines }}"

Upvotes: 2

Related Questions