From 10cc2839488975a2246f2b898b3d9ae4eb266756 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 26 Jan 2023 14:57:23 -0600 Subject: [PATCH] Add Loop Over A List Of Dictionaries as an Ansible TIL --- README.md | 7 ++++- ansible/loop-over-a-list-of-dictionaries.md | 33 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 ansible/loop-over-a-list-of-dictionaries.md diff --git a/README.md b/README.md index 45161f6..207e1db 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1277 TILs and counting..._ +_1278 TILs and counting..._ --- @@ -18,6 +18,7 @@ _1277 TILs and counting..._ * [Ack](#ack) * [Amplify](#amplify) +* [Ansible](#ansible) * [Chrome](#chrome) * [Clojure](#clojure) * [CSS](#css) @@ -85,6 +86,10 @@ _1277 TILs and counting..._ - [Sign Up User With Email And Password](amplify/sign-up-user-with-email-and-password.md) +### Ansible + +- [Loop Over A List Of Dictionaries](ansible/loop-over-a-list-of-dictionaries.md) + ### Chrome - [Access A Value Logged To The Console](chrome/access-a-value-logged-to-the-console.md) diff --git a/ansible/loop-over-a-list-of-dictionaries.md b/ansible/loop-over-a-list-of-dictionaries.md new file mode 100644 index 0000000..feb2e29 --- /dev/null +++ b/ansible/loop-over-a-list-of-dictionaries.md @@ -0,0 +1,33 @@ +# Loop Over A List Of Dictionaries + +Ansible's `loop` can iterate over a list of dictionaries in a task. That task +will be evaluated for each `item` in that list. Since each `item` is a +dictonary, we can access the fields on the `item` directory with dot notation — +`item.name`. + +Here is what this would look like for a task that is setting up authorized SSH +keys. + +```yaml +--- +- hosts: all + vars: + dev_users: + - name: alice + ssh_key_url: https://github.com/dev1.keys + - name: bob + ssh_key_url: https://github.com/dev2.keys + tasks: + - name: Set authorized keys taken from url + ansible.posix.authorized_key: + user: "{{ item.name }}" + state: present + key: "{{ item.ssh_key_url }}" + loop: "{{ dev_users }}" +``` + +Notice the `loop` over the `dev_users` variable gives us access to an `item` in +the task. Because each `item` has a `name` and an `ssh_key_url`, we can access +those fields in the task. + +[source](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_loops.html#standard-loops)