Skip to main content
 首页 » 编程设计

python之Ansible:给定变量中的整数列表,定义第二个列表,其中每个元素都递增

2024年10月17日8Free-Thinker

假设我们有一个 Ansible 变量,它是 list_of_ints。

我想定义一个incremented_list,它的元素是通过第一个列表的元素递增固定数量获得的。

例如,如果这是第一个变量:

--- 
# file: somerole/vars/main.yml 
 
list_of_ints: 
  - 1 
  - 7 
  - 8 

假设增量为 100,所需的第二个列表将包含以下内容:

incremented_list: 
  - 101 
  - 107 
  - 108 

我在想一些事情:

incremented_list: "{{ list_of_ints | map('add', 100) | list }}" 

遗憾的是,Ansible 有 custom filters for logarithms or powers ,但不适用于基本算术,因此我可以轻松计算这些数字的 log10,但不会增加它们。

任何想法,除了关于 https://github.com/ansible/ansible/blob/v2.1.1.0-1/lib/ansible/plugins/filter/mathstuff.py 的拉取请求?

请您参考如下方法:

这样做就可以了:

--- 
 
- hosts: localhost 
  connection: local 
  vars: 
    incremented_list: [] 
    list_of_ints: 
      - 1 
      - 7 
      - 8 
    incr: 100 
 
 tasks: 
   - set_fact: 
       incremented_list: "{{ incremented_list + [ item + incr ]  }}" 
     no_log: False 
     with_items: "{{ list_of_ints }}" 
 
   - name: show cntr 
     debug: var=incremented_list