Variables

Variable in playbooks are very similar to using variables in any programming language. It helps you to use and assign a value to a variable and use that anywhere in the playbook. One can put conditions around the value of the variables and accordingly use them in the playbook.

- hosts : <your hosts> 
vars:
tomcat_port : 8080 

we have defined a variable name tomcat_port and assigned the value 8080 to that variable and can use that in your playbook wherever needed.

Now taking a reference from the example shared. The following code is from one of the roles (install-tomcat) −

block: 
   - name: Install Tomcat artifacts 
      action: > 
      yum name = "demo-tomcat-1" state = present 
      register: Output 
          
   always: 
      - debug: 
         msg: 
            - "Install Tomcat artifacts task ended with message: {{Output}}" 
            - "Installed Tomcat artifacts - {{Output.changed}}" 

Keywords

  • block − Ansible syntax to execute a given block.

  • name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed.

  • action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml.

  • register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output.

  • always − Again a Ansible keyword , it states that below will always be executed.

  • msg − Displays the message.

Exception Handling

Exception handling in Ansible is similar to exception handling in any programming language.

tasks: 
   - name: Name of the task to be executed 
      block: 
         - debug: msg = 'Just a debug message , relevant for logging' 
         - command: <the command to execute> 
      
      rescue: 
         - debug: msg = 'There was an exception.. ' 
         - command: <Rescue mechanism for the above exception occurred) 
      
      always: 
         - debug: msg = "this will execute in all scenarios. Always will get logged" 

Keywords

  • rescue and always are the keywords specific to exception handling.

  • Block is where the code is written (anything to be executed on the Unix machine).

  • If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed.

  • Always gets executed in all cases.

  • So if we compare the same with java, then it is similar to try, catch and finally block.

  • Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally.

Last updated