I have a repeated pattern like this one::
- name: =code_01= clone repository
git: [email protected]:/code_01
dest=/tmp/code_01
update=yes
force=yes
accept_hostkey=yes
version=master
sudo: true
sudo_user: "{{ user }}"
- name: =code_01= egg build
shell: . {{ home }}/{{ venv_name }}/bin/activate && make egg
args:
chdir: "/tmp/code_01"
sudo_user: "{{ user }}"
sudo: true
- name: =code_01= egg get
command: find /tmp/code_01/dist -type f -iname '*.egg'
register: code_01eggs
- name: =code_01= egg install in {{ venv_name }} venv
shell: . {{ home }}/{{ venv_name }}/bin/activate && easy_install {{ item }}
args:
chdir: "{{ home }}"
with_items: "{{ code_01eggs.stdout_lines }}"
sudo_user: "{{ user }}"
sudo: true
- name: =code_01= cleanup
file: path=/tmp/code_01 state=absent
sudo: true
And I have this to do with: code_02, code_03, code_04, ..., code_0n
How can I "factorize" this ?
The resource models are idempotent meaning change commands are not run unless needed, and Ansible will bring the system back to a desired state regardless of the actual state – rather than you having to tell it how to get to the state.
Ansible offers two ways to re-use files and roles in a playbook: dynamic and static. For dynamic re-use, add an include_* task in the tasks section of a play: include_role. include_tasks.
You can move the logic to a second yml file and use include
with with_items
:
- include: factored.yml
with_items:
- code_01
- code_02
- code_03
And in the second file replace code_01
with {{ item }}
.
Useful link: Ansible docs: Loops and include
Note: if you have nested loops, you can set the outter loop item using set_fact
after Ansible 2.0. Refer to the above documentation for more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With