ML
    • Recent
    • Categories
    • Tags
    • Popular
    • Users
    • Groups
    • Register
    • Login

    Minimize conditionals with Ansible

    IT Discussion
    ansible conditionals roles linux devops
    1
    1
    700
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • stacksofplatesS
      stacksofplates
      last edited by stacksofplates

      So in Ansible you can use conditionals when a fact is different between systems (eg distribution, release, ip address, etc). You can also use variables with dictionaries and facts to accomplish this. Here is an example using a dictionary with package names for Apache:

      ---
      # vars file for test
      dist_hash:
          "RedHat":
              webserver: 'httpd'
          "Fedora":
              webserver: 'httpd'
          "Ubuntu":
              webserver: 'apache2'
      
      webserver: "{{ dist_hash[ansible_distribution]['webserver'] }}"
      

      The variable that will be called in the task is at the bottom. That variable references the hash (dictionary) above it. So it looks in dist_hash for the distribution (in my case Fedora) and replaces ansible_distribution with the actual name. Then it looks at the webserver value of the hash under that distribution name.

      I set up a simple task that copies a template called test.j2 with these contents:

      We will install {{ webserver }} on this system.
      

      The main task file is this:

      ---
      # tasks file for test
      - name: test
        template:
          src: test.j2
          dest: /tmp/test.conf
          owner: root
          group: root
          mode: 0644
      

      So it copies test.j2 and fills in the variable and stores it as /tmp/test.conf. Here's the output of that file:

      [jhooks@starscream tmp]$ cat test.conf 
      We will install httpd on this system.
      

      This is one way to keep conditionals to a minimum in your roles.

      1 Reply Last reply Reply Quote 4
      • 1 / 1
      • First post
        Last post