Best Practices for Using Arithmetic Operators in Ansible Playbooks

Ansible provides several ways to perform arithmetic operations in your playbook tasks, such as adding, subtracting, multiplying, and dividing numbers.

Here are some examples of how to use arithmetic operators in Ansible:
  1. Using the set_fact module to define a variable with the result of an arithmetic operation:
yaml
- name: Calculate the sum of two variables 
 set_fact:  
    result: "{{ var1 + var2 }}"  
- name: Calculate the difference of two variables  
    set_fact:  
        result: "{{ var1 - var2 }}" 
- name: Calculate the product of two variables 
    set_fact: 
        result: "{{ var1 * var2 }}" 
 - name: Calculate the quotient of two variables  
    set_fact: 
        result: "{{ var1 / var2 }}"
  1. Using the with_sequence loop to generate a sequence of numbers and perform an arithmetic operation:
yaml
- name: Generate a sequence of numbers and calculate the square of each number set_fact:  
    squares: "{{ squares|default([]) + [item * item] }}"  
   with_sequence: start=1 end=10  
- name: Generate a sequence of numbers and calculate the cube of each number set_fact:  
    cubes: "{{ cubes|default([]) + [item ** 3] }}" 
    with_sequence: start=1 end=10
  1. Using the with_items loop to perform an arithmetic operation on each item in a list:
yaml
- name: Multiply each item in the list by 2  
    set_fact: 
    doubled_list: "{{ doubled_list|default([]) + [item * 2] }}" 
 with_items: "{{ original_list }}" 
 - name: Divide each item in the list by 2  
set_fact:  
    halved_list: "{{ halved_list|default([]) + [item / 2] }}" with_items: "{{ original_list }}"

Note that in these examples, the default filter is used to initialize the variables squares, cubes, doubled_list, and halved_list to an empty list if they haven't been defined yet.

أحدث أقدم