Looping and Error handling

25 views
Skip to first unread message

megha sharma

unread,
Jul 5, 2016, 8:44:29 AM7/5/16
to Ansible Project
I am trying to add multiple users on my machine using Looping concept in ansible. Along with that I want to handle the errors occur when i try to add a user that already exists.But I am not able to rescue each iteration.

This is my code:
#Users that I am trying to add already exists


- name: Add a user
  hosts: server
  gather_facts: false
  tasks:
    - name: Create Group
      win_group:
        name: TestGroup
        state: present
    - block:
        - name: Adding Multiple Users
          win_user: name={{ item.name }} password={{ item.password }} state=present groups={{ item.groups }}
          register: AddUser
          with_items:
            - { name: 'testuser1', password: 'test1@123', groups: 'TestGroup' }
            - { name: 'testuser2', password: 'test2@123', groups: 'TestGroup' }
      rescue:
        - debug: msg='Command failed...please check...may be User Already exists'
          when: "'FAILED' in AddUser"

Output :

PLAY [Add a user] **************************************************************

TASK [Create Group] ************************************************************
ok: [10.155.101.39]

TASK [Adding Multiple Users] ***************************************************
failed: [10.155.101.39] => (item={u'password': u'infy@123', u'name': u'testuser1', u'groups': u'TestGroup'}) => {"failed": true, "item": {"groups": "TestGroup", "name": "testuser1", "password": "infy@123"}, "msg": "Exception calling \"ValidateCredentials\" with \"2\" argument(s): \"The network path was not found.\r\n\""}
failed: [10.155.101.39] => (item={u'password': u'infy@123', u'name': u'testuser2', u'groups': u'TestGroup'}) => {"failed": true, "item": {"groups": "TestGroup", "name": "testuser2", "password": "infy@123"}, "msg": "Exception calling \"ValidateCredentials\" with \"2\" argument(s): \"The network path was not found.\r\n\""}

TASK [debug] *******************************************************************
ok: [10.155.101.39] => {
    "msg": "Command failed...please check...may be User Already exists"
}

PLAY RECAP *********************************************************************
10.155.101.39              : ok=2    changed=0    unreachable=0    failed=0

Reply all
Reply to author
Forward
0 new messages