{"id":2785,"date":"2024-08-28T15:39:48","date_gmt":"2024-08-28T15:39:48","guid":{"rendered":"https:\/\/blog.samarthya.me\/wps\/?p=2785"},"modified":"2024-08-28T18:02:11","modified_gmt":"2024-08-28T18:02:11","slug":"ansible-loops","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2024\/08\/28\/ansible-loops\/","title":{"rendered":"Ansible Loops"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2024\/08\/loop-1-1024x1024.jpeg\" alt=\"\" class=\"wp-image-2786\" srcset=\"https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2024\/08\/loop-1-1024x1024.jpeg 1024w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2024\/08\/loop-1-150x150@2x.jpeg 300w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2024\/08\/loop-1-150x150.jpeg 150w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2024\/08\/loop-1.jpeg 1536w, https:\/\/blog.samarthya.me\/wps\/wp-content\/uploads\/2024\/08\/loop-1-300x300@2x.jpeg 600w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p><code>Ansible<\/code> offers powerful looping mechanisms that can significantly enhance your playbooks&#8217; efficiency and readability. In this blog post, we&#8217;ll dive deep into Ansible loops, exploring various elements and providing practical examples to help you master this essential feature.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Table of Contents<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#introduction-to-loops\">Introduction to Loops<\/a><\/li>\n\n\n\n<li><a href=\"#basic-loop-usage\">Basic Loop Usage<\/a><\/li>\n\n\n\n<li><a href=\"#loop-control-and-loop_var\">loop_control and loop_var<\/a><\/li>\n\n\n\n<li><a href=\"#looping-over-dictionaries\">Looping Over Dictionaries<\/a><\/li>\n\n\n\n<li><a href=\"#nested-loops\">Nested Loops<\/a><\/li>\n\n\n\n<li><a href=\"#using-loops-with-include-statements\">Using Loops with Include Statements<\/a><\/li>\n\n\n\n<li><a href=\"#advanced-loop-techniques\">Advanced Loop Techniques<\/a><\/li>\n\n\n\n<li><a href=\"#best-practices-and-tips\">Best Practices and Tips<\/a><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to Loops<\/h2>\n\n\n\n<p>Loops in <code>Ansible<\/code> allow you to repeat a task multiple times with different input values. This can dramatically reduce the amount of code you need to write and maintain, making your playbooks more efficient and easier to read.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Loop Usage<\/h2>\n\n\n\n<p>The most common way to use loops in <code>Ansible<\/code> is with the <code>loop<\/code> keyword. Here&#8217;s a simple example:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-light-green-cyan-background-color has-text-color has-background has-link-color has-medium-font-size wp-elements-47599df56619d897f1de621a303b9ee9\"><code><code>- name: Ensure multiple users exist\n  ansible.builtin.user:\n    name: \"{{ item }}\"\n    state: present\n  loop:\n    - john\n    - jane\n    - bob<\/code><\/code><\/pre>\n\n\n\n<p>In this example, the task will run three times, creating users named <code>john<\/code>, <code>jane<\/code>, and <code>bob<\/code>. The loop variable <code>item<\/code> takes on each value in the list.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><code>loop_control<\/code> and <code>loop_var<\/code><\/h2>\n\n\n\n<p>The <code>loop_control<\/code> directive allows you to fine-tune how your loops behave. One of its most useful features is <code>loop_var<\/code>, which lets you rename the loop variable:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-light-green-cyan-background-color has-text-color has-background has-link-color has-medium-font-size wp-elements-fffcd9d6cae27aeaec817b004b048490\"><code><code>- name: Install multiple packages\n  ansible.builtin.apt:\n    name: \"{{ package }}\"\n    state: present\n  loop:\n    - nginx\n    - postgres\n    - redis\n  loop_control:\n    loop_var: package<\/code><\/code><\/pre>\n\n\n\n<p>Here, we&#8217;ve used <code>loop_var: package<\/code> to rename the loop variable from <code>item<\/code> to <code>package<\/code>, making the playbook more readable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Looping Over Dictionaries<\/h2>\n\n\n\n<p>Loops become even more powerful when working with dictionaries:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-light-green-cyan-background-color has-text-color has-background has-link-color has-medium-font-size wp-elements-b09368db9f50acfe86df74cc50ff007f\"><code><code>- name: Create multiple users with specific properties\n  ansible.builtin.user:\n    name: \"{{ user.name }}\"\n    groups: \"{{ user.groups }}\"\n    state: present\n  loop:\n    - { name: 'john', groups: 'admins' }\n    - { name: 'jane', groups: 'developers' }\n    - { name: 'bob', groups: 'support' }\n  loop_control:\n    loop_var: user<\/code><\/code><\/pre>\n\n\n\n<p>This example demonstrates how to loop over a list of dictionaries, creating users with specific properties.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Nested Loops<\/h2>\n\n\n\n<p>Ansible supports nested loops, allowing you to iterate over multiple lists:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-pale-cyan-blue-background-color has-text-color has-background has-link-color wp-elements-62e7a0ac44104b8b78f53facf59e7fba\"><code>---\n# sample-loop.yml\n- name: Print outer and inner items\n  ansible.builtin.debug:\n    msg: \"outer item={{ outer_item }} inner item={{ item }}\"\n  loop:\n    - a\n    - b\n    - c\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-black-color has-light-green-cyan-background-color has-text-color has-background has-link-color has-medium-font-size wp-elements-4e8a6710a78bb522da21f11fac9342e2\"><code><code><span style=\"background-color: initial; font-family: inherit; font-size: inherit;\">    - include_tasks: sample-loop.yml<\/span><\/code>      loop:\n        - 1\n        - 2\n        - 3\n      loop_control:\n        loop_var: outer_item<\/code><\/pre>\n\n\n\n<p>This loops through two loops<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-vivid-cyan-blue-background-color has-text-color has-background has-link-color wp-elements-3d4fd19cb1f14d6127d0b373193a500b\"><code>ok: &#91;localhost] => (item=a) => {\n    \"msg\": \"outer item=1 inner item=a\"\n}\nok: &#91;localhost] => (item=b) => {\n    \"msg\": \"outer item=1 inner item=b\"\n}\nok: &#91;localhost] => (item=c) => {\n    \"msg\": \"outer item=1 inner item=c\"\n}\nok: &#91;localhost] => (item=a) => {\n    \"msg\": \"outer item=2 inner item=a\"\n}\nok: &#91;localhost] => (item=b) => {\n    \"msg\": \"outer item=2 inner item=b\"\n}\nok: &#91;localhost] => (item=c) => {\n    \"msg\": \"outer item=2 inner item=c\"\n}\nok: &#91;localhost] => (item=a) => {\n    \"msg\": \"outer item=3 inner item=a\"\n}\nok: &#91;localhost] => (item=b) => {\n    \"msg\": \"outer item=3 inner item=b\"\n}\nok: &#91;localhost] => (item=c) => {\n    \"msg\": \"outer item=3 inner item=c\"\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Using Loops with Include Statements<\/h2>\n\n\n\n<p>Loops can be used with <code>include_tasks<\/code> to dynamically include task files:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-light-green-cyan-background-color has-text-color has-background has-link-color has-medium-font-size wp-elements-881799520b3ae1c58230842722a3b7a3\"><code><code>- name: Include task file for each user\n  include_tasks: user_setup.yml\n  loop:\n    - { name: 'john', role: 'admin' }\n    - { name: 'jane', role: 'developer' }\n  loop_control:\n    loop_var: current_user<\/code><\/code><\/pre>\n\n\n\n<p>This includes and executes the <code>user_setup.yml<\/code> task file for each user in the loop.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Advanced Loop Techniques<\/h2>\n\n\n\n<p>Ansible offers several advanced looping techniques:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>with_items<\/strong>: An older syntax, still supported but <code>loop<\/code> is preferred.<\/li>\n\n\n\n<li><strong>with_dict<\/strong>: For iterating over dictionary key-value pairs.<\/li>\n\n\n\n<li><strong>with_fileglob<\/strong>: For looping over files matching a pattern.<\/li>\n\n\n\n<li><strong>with_sequence<\/strong>: For generating a sequence of items to iterate over.<\/li>\n<\/ol>\n\n\n\n<p>Example of <code>with_sequence<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-light-green-cyan-background-color has-text-color has-background has-link-color wp-elements-a77e8fae1e97bc27b8e74d8875e25f39\"><code><code>- name: Create multiple directories\n  ansible.builtin.file:\n    path: \"\/tmp\/dir{{ item }}\"\n    state: directory\n  with_sequence: start=1 end=5 format=\"%02d\"<\/code><\/code><\/pre>\n\n\n\n<p>This creates directories named dir01 through dir05.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices and Tips<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Use meaningful names for your loop variables with <code>loop_var<\/code>.<\/li>\n\n\n\n<li>Keep your loops simple and readable. If a loop becomes too complex, consider breaking it into separate tasks.<\/li>\n\n\n\n<li>Use <code>loop<\/code> instead of <code>with_items<\/code> for better performance and consistency.<\/li>\n\n\n\n<li>Be mindful of the performance impact when looping over large datasets.<\/li>\n\n\n\n<li>Use <code>loop_control: label<\/code> to customize the output of your loops for better readability in Ansible output.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Happy looping!<\/h2>\n","protected":false},"excerpt":{"rendered":"<p>Ansible offers powerful looping mechanisms that can significantly enhance your playbooks&#8217; efficiency and readability. In this blog post, we&#8217;ll dive deep into Ansible loops, exploring various elements and providing practical examples to help you master this essential feature. Table of Contents Introduction to Loops Loops in Ansible allow you to repeat a task multiple times [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":2787,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[34],"tags":[278],"class_list":["post-2785","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technical","tag-ansible"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/2785","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=2785"}],"version-history":[{"count":2,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/2785\/revisions"}],"predecessor-version":[{"id":2790,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/2785\/revisions\/2790"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media\/2787"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=2785"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=2785"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=2785"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}