Ansible pass result of a task as an input to another task in role

237 views
Skip to first unread message

RajG

unread,
Dec 10, 2021, 9:38:20 AM12/10/21
to Ansible Project

This is my Ansible playbook ...

roles/myrole ├── defaults │   └── main.yml ├── tasks │   ├── add_user_to_group.yml │   ├── create_user.yml │   └── main.yml ├── templates │   ├── add_user_to_group_data.j2 │   └── create_user_data.j2 └── vars     └── main.yml


role/myrole/tasks/create_user.yml

--- - name: Creating User ...   uri:     url: https://www.example.com/api/users     method: POST     body: "{{ create_user_data }}"     body_format: json     status_code: 200     return_content: yes     headers:       Accept: application/json       Content-Type: application/json       x-api-key: my-api-key-here   register: result - name: Saving User ID to a Variable   set_fact:     user_create_id:       result: "{{ result.json | community.general.json_query('id') }}" - name: Printing User ID of the User Created   ansible.builtin.debug:     msg: "{{ user_create_id }}"


tasks/add_user_to_group.yml

--- - name: Adding User to Group ...   uri:       url: https://www.example.com/api/usergroups/123456/members     method: POST     body: "{{ add_user_to_group_data }}"     body_format: json     status_code: 200     return_content: yes     headers:       Accept: application/json       Content-Type: application/json       x-api-key: my-api-key-here   register: result


templates/create_user_data.j2

{     "username":"john",     "email":"jo...@gmail.com",     "firstname":"John",     "lastname":"Smith" }


templates/add_user_to_group_data.j2

{     "op": "add",     "type": "user",     "id": "{{ user_create_id }}" }


vars/main.yml

create_user_data: "{{ lookup('template', 'create_user_data.j2') }}" add_user_to_group_data: "{{ lookup('template', 'add_user_to_group_data.j2') }}"


Output of task create_user.yml printing the ID

ok: [localhost] => {     "msg": {         "result": "71b248b35ea374433153bbe4"     } }


I run the playbook basefile.yml which has the role myrole.

I'm trying to pass the ID from the result of the task create_user.yml as an input variable to the another task add_user_to_group.yml, especially in the template add_user_to_group_data.j2.

I unable to pass the variable {{ create_user_id }} to add_user_to_group_data.j2. If possible, we can create another task and call both the tasks passing some variables or to template file, but don't know how. 

How do I pass the json output field value from a task as an input to another task in the role?, any help is appreciated!.


Thanks in advance!

Reply all
Reply to author
Forward
0 new messages