<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Noe Gonzalez</title>
    <description>The latest articles on DEV Community by Noe Gonzalez (@engonzal).</description>
    <link>https://dev.to/engonzal</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F98206%2F32416f9e-8861-4648-a8f4-e2fdf3223886.png</url>
      <title>DEV Community: Noe Gonzalez</title>
      <link>https://dev.to/engonzal</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/engonzal"/>
    <language>en</language>
    <item>
      <title>Using Ansible “when” Statements</title>
      <dc:creator>Noe Gonzalez</dc:creator>
      <pubDate>Mon, 12 Nov 2018 15:25:53 +0000</pubDate>
      <link>https://dev.to/engonzal/using-ansible-when-statements-d47</link>
      <guid>https://dev.to/engonzal/using-ansible-when-statements-d47</guid>
      <description>

&lt;p&gt;Using Ansible “when” statements allows you to set parameters for when a task should play out.  I’ve put together some examples of how to use basic when statements that I’ve come across.&lt;/p&gt;

&lt;h2&gt;Booleans (True or False)&lt;/h2&gt;

&lt;p&gt;In the example playbook below, I print “Hello world” when the”test_var” variable is true.  In the case below we use the “bool” filter to make test_var evaluated as a boolean (ie true or false), then ensure it’s true:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- hosts: localhost
  user: engonzal
  connection: local
  tasks:
    - name: test_var is "{{ test_var }}"
      debug: msg="Hello world."
      when: test_var|bool == true
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As a note, instead of using “test_var|bool == true”, you can simply use “when: test_var”.  To evaluate when test_vars is false you would use “test_var|bool == false”&lt;/p&gt;

&lt;h2&gt;Defined Variables&lt;/h2&gt;

&lt;p&gt;Sometimes you’ll want to check if a variable is defined before running a task, or another when statement.  The example below has two tasks, the first runs when “test_var” is defined.  the second runs when “test_var” is not defined.  Since we’re defining “test_var” in the playbook “vars” section, the second task will show as “skipped”&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- hosts: localhost
  user: engonzal
  connection: local
  vars:
    test_var: true
  tasks:
    - name: test_var is "{{ test_var }}" (when defined)
      debug: msg="test_var is defined"
      when: test_var is defined

    - name: test_var is "{{ test_var }}" (when not defined)
      debug: msg="test_var is not defined"
      when: test_var is not defined
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;Combing Tests&lt;/h2&gt;

&lt;p&gt;We also have the option of combining variables with “and”.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- hosts: localhost
  user: engonzal
  connection: local
  vars:
    dog: true
  tasks:
    - name: dog is defined, cat is defined
      debug: msg="Hello dog and cat."
      when: dog is defined and cat is defined

    - name: dog is defined or cat is defined
      debug: msg="Hello dog or cat."
      when: dog is defined or cat is defined
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You can also format “and” statements as items of “when”&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    - name: dog is defined, cat is defined
      debug: msg="Hello dog and cat."
      when:
        - dog is defined
        - cat is defined
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;String Tests&lt;/h2&gt;

&lt;p&gt;You can also use a when statement to verify a variable is equal to a string.  In the example below we check that “dog” is equal to “bone”.  Note that I use “dog | lower”.  This converts all the characters in the dog variable to lower case.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- hosts: localhost
  user: engonzal
  connection: local
  vars:
    dog: bone
  tasks:
    - name: dog is bone, cat is undefined
      debug: msg="dog is equal to bone"
      when: dog|lower == "bone"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now let’s look at cat, notice that since we don’t define cat in the vars section, we want to first check if cat is defined.  This task will skip because cat is not defined and the “cat|lower ==”fish” will not get evaluated.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    - name: cat is equal to fish
      debug: msg="cat likes fish"
      when:
        - cat is defined
        - cat|lower == "fish"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Alternatively you can use the defaults filter to use a default value for “cat”&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    - name: cat is equal to fish
      debug: msg="cat is equal to fish"
      when: cat | default('fish') | lower == "fish"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;Verify a file exists&lt;/h2&gt;

&lt;p&gt;You can use the “stat” module to check if a file or directory exists.  All you need to do is run the stat module, and add the “register: my_new_variable”.  We can then evaluate that variable:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- hosts: localhost
  user: engonzal
  connection: local
  tasks:
    - name: Check if /tmp exists
      stat:
        path: /tmp
      register: stat_tmp

    - name: Say Hello when "/tmp" exists
      debug: msg="Hi! the directory /tmp exists"
      when:
        - stat_tmp.stat.exists|bool == true
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;Find Strings&lt;/h2&gt;

&lt;p&gt;You can also use the find filter to check if something exists in a variable.  In the example below, we’re checking if the variable “cat” contains any occurence of the word “plays”.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- hosts: localhost
  user: engonzal
  connection: local
  vars:
    cat: "cat plays with yarn"
  tasks:
    - name: Check if cat "plays"
      debug: msg="The cat does play"
      when: cat.find("plays") != -1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Having the flexibility to only run tasks when they’re needed is a useful feature of Ansible.  The built in tests allow you a lot of freedom for how to structure playbooks and roles.  These were some basic example, but they can get pretty complicated.  &lt;a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html"&gt;Ansible’s docs&lt;/a&gt; also have some other great examples of how to use “tests”. &lt;/p&gt;

&lt;p&gt;I’ll be putting together some more interesting examples in the future!  Take a look at the guide to &lt;a href="https://dev.to/engonzal/setup-ansible-with-python-virtualenv-38go-temp-slug-4960710"&gt;setting up ansible with virtualenv&lt;/a&gt; if you’re new.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://buildahomelab.com/2018/11/12/using-ansible-when-statements/"&gt;Using Ansible “when” Statements&lt;/a&gt; appeared first on &lt;a href="https://buildahomelab.com"&gt;Build a Homelab&lt;/a&gt;.&lt;/p&gt;


</description>
      <category>ansible</category>
      <category>linux</category>
      <category>configmanagement</category>
      <category>playbook</category>
    </item>
    <item>
      <title>Using subelements in Ansible to loop through multiple lists.</title>
      <dc:creator>Noe Gonzalez</dc:creator>
      <pubDate>Sat, 03 Nov 2018 17:33:16 +0000</pubDate>
      <link>https://dev.to/engonzal/using-subelements-in-ansible-to-loop-through-multiple-lists-1h2i</link>
      <guid>https://dev.to/engonzal/using-subelements-in-ansible-to-loop-through-multiple-lists-1h2i</guid>
      <description>&lt;p&gt;While working on my Ansible Galaxy &lt;a href="https://galaxy.ansible.com/engonzal/users"&gt;users role&lt;/a&gt; I came across a situation where I needed to loop through a list inside a dictionary inside a list.  For this specific case I had a list of users, and each user could have multiple authorized sshkeys stored in a “pubkeys” value.  To add each sshkey I used subelements in Ansible to loop through multiple lists.&lt;/p&gt;

&lt;p&gt;Here’s an example variable.  Note that there are two users, one user has two public keys, and the other has one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;host\_local\_users:
 - name: user1
 pubkeys:
 - 'ssh-rsa myr4nd0mk3y engonzal@home'
 - 'ssh-rsa my000r4nd0m000k3y000tw0 engonzal@workstation'
 - name: user2
 pubkeys:
 - 'ssh-rsa myr4nd0mk3y engonzal@home'
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating a Task
&lt;/h2&gt;

&lt;p&gt;In this case “host_local_users” is a list.  Each item of “host_local_users” is a dictionary.  The key “pubkeys” is a list.  Now say we want to have a task that adds each key under pubkeys for the user in “name”.  That would look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- name: Add public keys to authorized\_hosts
 authorized\_key:
 user: "{{ item.0.name }}"
 state: "{{ item.0.state | default('present') }}"
 key: "{{ item.1 }}"
 loop: "{{ host\_local\_users | subelements('pubkeys', 'skip\_missing=True') }}"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;There’s a lot going on in this one task!  First note that the “loop” parameter is using our “host_local_users” variable.  We’re using the “subelements” filter to pick out the list of ssh keys for each user.  Each item of host_local_users is represented by “item.0”.  Each item of pubkeys is represented by “item.1” (note that we provided ‘pubkeys’ to the “subelements” filter).  &lt;/p&gt;

&lt;h2&gt;
  
  
  Running the task
&lt;/h2&gt;

&lt;p&gt;In practice this will run the authorized_key task 3 times even though there are only two users, it looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TASK [engonzal.users : Add public keys to authorized_hosts] ********************
changed: [instance] =&amp;gt; (item=[{u'pubkeys': [u'ssh-rsa myr4nd0mk3y engonzal@home', u'ssh-rsa my000r4nd0m000k3y000tw0 engonzal@workstation'], u'name': u'user1'}, u'ssh-rsa myr4nd0mk3y engonzal@home'])

changed: [instance] =&amp;gt; (item=[{u'pubkeys': [u'ssh-rsa myr4nd0mk3y engonzal@home', u'ssh-rsa my000r4nd0m000k3y000tw0 engonzal@workstation'], u'name': u'user1'}, u'ssh-rsa my000r4nd0m000k3y000tw0 engonzal@workstation'])

changed: [instance] =&amp;gt; (item=[{u'pubkeys': [u'ssh-rsa myr4nd0mk3y engonzal@home'], u'name': u'user2'}, u'ssh-rsa myr4nd0mk3y engonzal@home'])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This run added two ssh pubkeys for user1 and one ssh pubkey for user2 based on what we put in the variable “host_local_users”.&lt;/p&gt;

&lt;p&gt;I thought it was pretty cool that Ansible allowed these types of complex variables.  Many would argue that for some problems it makes more sense to use bash or a programming language for complicated tasks.  I’ve found that making those scripts idempotent adds a whole other layer of complexity that Ansible already has baked in.&lt;/p&gt;

&lt;p&gt;To get Ansible setup checkout my post on how to &lt;a href="https://dev.to/engonzal/setup-ansible-with-python-virtualenv-38go-temp-slug-4960710"&gt;install Ansible using virtualenvs.&lt;/a&gt;  To see subelements in practice take a look at the tasks in my &lt;a href="https://github.com/engonzal/ansible_role_users/blob/master/tasks/main.yml"&gt;“users” role on Github.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://buildahomelab.com/2018/11/03/subelements-ansible-loop-nested-lists/"&gt;Using subelements in Ansible to loop through multiple lists.&lt;/a&gt; appeared first on &lt;a href="https://buildahomelab.com"&gt;Build a Homelab&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>ansible</category>
      <category>galaxy</category>
      <category>lists</category>
      <category>loops</category>
    </item>
  </channel>
</rss>
