Ansible is known for its simplicity, lightweight footprint and flexibility to configure nearly any device in your infrastructure. Therefore it’s used in large scale environments shared between teams or departments. Often tasks could be used in multiple playbooks to combine update routines, setting downtimes at an API or update data at the central asset management.
To use external tasks in Ansible we use the include_task module. This module dynamically includes the tasks from the given file. When used in a specific plays we would assign play specific variables to avoid confusion. For example:
vim tasks/get_ldap_user.yml
- name: get user from ldap
register: users
community.general.ldap_search:
bind_pw: "{{ myplay_ad_bind_pw }}"
bind_dn: "{{ myplay_ad_bind_dn }}"
server_uri: "{{ myplay_ad_server }}"
dn: "{{ myplay_ad_user_dn }}"
filter: "(&(ObjectClass=user)(objectCategory=person)(mail={{ myplay_usermail }}))"
scope: children
attrs:
- cn
- mail
- memberOf
- distinguishedName
If this task should be used in another playbook to reduce the amount of code or is used again with other conditions or values. Therefore the variables need to be overwritten or if it is another playbook the variables are named wrong.
The solve this problem change the variables to unused generic variables. And assign your own variables in the include_task statement.
vim tasks/get_ldap_user.yml
- name: get user from ldap
register: users
community.general.ldap_search:
bind_pw: "{{ _ad_bind_pw }}"
bind_dn: "{{ _ad_bind_dn }}"
server_uri: "{{ _ad_server }}"
dn: "{{ _ad_user_dn }}"
filter: "(&(ObjectClass=user)(objectCategory=person)(mail={{ _ad_usermail }}))"
scope: children
attrs:
- cn
- mail
- memberOf
- distinguishedName
The include_task vars parameter provides own variables to the tasks.
vim plays/user_management.yml
[...]
- name: check if user exists in ldap
include_tasks:
file: tasks/get_ldap_user.yml
vars:
_ad_bind_pw: "{{ play_ad_pw }}"
_ad_bind_dn: "{{ play_ad_user }}"
_ad_server: "{{ play_ad_server }}"
_ad_user_dn: "OU=users,DC=example,DC=de"
_ad_usermail: "{{ play_usermail }}"
This can be easily combined with loops, to enhance the reusability of your tasks even more! Checkout this blogpost about looping multiple tasks. Ansible – Loop over multiple tasks
Check out our Blog for more awesome posts and if you need help with Ansible send us a message or sign up for one of our trainings!

0 Kommentare