在Ansible中进行算术运算可以使用Jinja2模板的表达式语法。下面是一个包含代码示例的解决方法:
创建一个Ansible playbook文件,比如arithmetic_operations.yml
。
在playbook文件中定义一个变量,比如number1
和number2
,并赋予它们相应的值。
---
- name: Arithmetic Operations
hosts: localhost
gather_facts: false
vars:
number1: 10
number2: 5
tasks:
- name: Print Addition
debug:
msg: "{{ number1 + number2 }}"
- name: Print Subtraction
debug:
msg: "{{ number1 - number2 }}"
- name: Print Multiplication
debug:
msg: "{{ number1 * number2 }}"
- name: Print Division
debug:
msg: "{{ number1 / number2 }}"
ansible-playbook arithmetic_operations.yml
输出结果将显示四种算术运算的结果:
PLAY [Arithmetic Operations] ***************************************************
TASK [Print Addition] **********************************************************
ok: [localhost] => {
"msg": "15"
}
TASK [Print Subtraction] *******************************************************
ok: [localhost] => {
"msg": "5"
}
TASK [Print Multiplication] ****************************************************
ok: [localhost] => {
"msg": "50"
}
TASK [Print Division] **********************************************************
ok: [localhost] => {
"msg": "2.0"
}
PLAY RECAP *********************************************************************
localhost : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
这样你就可以在Ansible中使用算术运算了。