ansible7:ansible过滤器

说明

  ansible中的过滤器功能来自于jinja2模板引擎,它是一种帮助我们处理数据的工具。有些过滤器是jinja2内置的,有些是ansible特有的,如果这些过滤器都不能满足你的需求,jinja2也支持自定义过滤器。

字符串过滤器

  1. upper:过滤数据,将小写字母变成大写。

      0 19:46:13 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test1.yaml
    ---
    - hosts: ck-node1
      vars:
        var1: 121b3cd
      tasks:
      - debug:
          msg: "{{var1|upper}}"
      0 19:46:15 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test1.yaml
    
  2. lower:将大写字母变成小写。

  3. capitalize:将字符串的首字母变为大写,后面的字母变为小写。

  4. reverse:将字符串反转。

  5. first:返回字符串的第一个字符。

  6. last:返回字符串的最后一个字符。

  7. trim:去除字符串开头和结尾的空格。

  8. center:字符串居中显示。center(width=30)表示字符串居中显示,两侧用空格补全30位。

  9. count和length:返回字符串长度。

  10. list:将字符串转换成列表,每个字符作为一个元素。

  11. shuffle:将字符串转换成列表,每个字符作为一个元素,随机打乱顺序。

数字过滤器

  1. int:将对应的值转换为int类型。

      0 19:52:06 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test2.yaml
    ---
    - hosts: ck-node1
      vars:
        var1: '50'
      tasks:
      - debug:
          msg: "{{2+(var1|int)}}"	# 字符串和整形不能直接计算,所以需要对var1变量进行int转换。
      0 19:52:07 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test2.yaml
    # 如果无法转换为int类型,默认返回0。个性化指定返回值,比如返回6:{{ 'a' | int(6) }}
      0 19:55:22 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test3.yaml
    ---
    - hosts: ck-node1
      vars:
        var1: 'a'
      tasks:
      - debug:
          msg: "{{2+(var1|int)}}"	# 默认返回0,如果想个性化指定返回值,比如返回8,那可以写成:msg: "{{2+(var1|int(8))}}"
      0 19:55:23 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test3.yaml
    
  2. float:对应的值转换为浮点型。如果无法转换,默认返回‘0.0’,个性化指定返回值,比如返回8.8:{{ 'a' | float(8.8) }}。

  3. abs:获取对应值的绝对值。

  4. round:四舍五入。取小数点后五位{{ 3.1415926 | round(5) }}。

  5. random:取随机数。

    • 从0到100中随机返回一个随机数:{{ 100 | random }}。
    • 从5到10中随机返回一个随机数:{{ 10 | random(start=5) }}
    • 从0到15中随机返回一个随机数,这个随机数是5的倍数:{{ 15 | random(step=5) }}

列表过滤器

  1. length、count、first、las、shuffle、upper、lower与上面字符串过滤器作用一致。

  2. min:取列表中的最小值。

      0 19:58:32 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test4.yaml
    ---
    - hosts: ck-node1
      vars:
        var1: [1,'b',2,'a','e']
      tasks:
      - debug:
          msg: "{{var1|min}}"
      0 19:58:34 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test4.yaml
    
  3. max:取列表中的最大值。

  4. sort:排序

    • 将列表升序排序输出:{{ var | sort }}
    • 将列表降序排序输出:{{ var | sort(reverse=true) }}
  5. sum:求纯数字列表中数字的和。

  6. flatten:拉平列表

    • 将嵌套列表展开平铺:{{ var | flatten }}
    • 只展开第一层的嵌套列表:{{ var | flatten(levels=1) }}
    • 取嵌套列表中的最大值:{{ var | flatten | max }}
  7. join:

    • 将列表中的元素合并成一个字符串:{{ var | join }}
    • 将列表中的元素合并成一个字符串,每个元素之间用指定的字符隔开:{{ var | join('😂 }}
  8. random:从列表中返回一个元素,对列表使用random过滤器时,不能使用start和step参数。{{ var | random }}

  9. unique:去除重复的元素。{{var | unique}}

  10. union:合并列表,也就是求列表的并集。{{ var1 | union(var2) }}

  11. intersect:求列表的交集。{{ var1 | intersect(var2) }}

  12. difference:取出存在于var1列表中,但不存在于var2列表中的元素。{{ var1 | difference(var2) }}

  13. symmetric_difference:取出两个列表中各自独有的元素,重复的元素只留下一个。{{var1 | symmetric_difference(var2)}}

其它过滤器

  1. default:

    • 如果变量没有定义,临时返回一个指定好的默认值。
      0 20:01:10 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test5.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{var1|default('wula')}}"
      0 20:01:15 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test5.yaml
    
    • 如果变量的值是一个空字符串或者变量没有定义,临时返回一个指定的默认值。
      0 20:04:14 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test6.yaml
    ---
    - hosts: ck-node1
      vars:
        var1: 'natasha'
      tasks:
      - debug:
          msg: "{{var1|default('wula',boolean=true)}}"
      0 20:04:16 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test6.yaml
    
    • default过滤器还可能帮我们实现差异配置,比如要创建三个文件,有些文件要设置权限属性,有些不要(此处牵扯到with_item循环可在第8节查看)。
    # 第一种方式:使用循环实现。
      0 20:27:55 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test7.yaml
    ---
    - hosts: ck-node1
      vars:
        paths:
          - path: /root/file1
            mode: '0666'
          - path: /root/file2
          - path: /root/file3
      tasks:
      - file: path={{item.path}} state=touch mode={{item.mode}}
        with_items: "{{paths}}"
        when: item.mode is defined
      - file: path={{item.path}} state=touch
        with_items: "{{paths}}"
        when: item.mode is undefined
      0 20:28:14 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test7.yaml
    # 第二种方式:使用过滤器实现。
    ## {{item.mode | default(omit):}}:如果item有mode,就调用mode属性的值,如果没有就忽略mode参数。
      0 20:30:03 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test8.yaml
    ---
    - hosts: ck-node1
      vars:
        paths:
          - path: /root/file1
            mode: '0666'
          - path: /root/file2
          - path: /root/file3
      tasks:
      - file: dest={{item.path}} state=touch mode={{item.mode | default(omit)}}
        with_items: "{{paths}}"
      0 20:30:14 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test8.yaml
    
  2. 如果变量未定义,则报出“Mandatory variable not defined.”错误,而不是报出默认错误:{{var5 | mandatory}}

  3. json_query:取出bob的爱好。

      0 14:00:02 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat variables.yaml 
    ---
    users:
    - name: bob
      age: 18
      hobby:
       - swimming
       - runnning
    - name: zoe
      age: 20
      hobby:
       - music
      0 14:00:09 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test9.yaml
    ---
    - hosts: ck-master
      tasks:
      - include_vars: 
          file: /server/ops_ansible/variables.yaml
          name: var1
      - debug:
          msg: "{{ var1 | json_query('users[?name==`bob`].hobby[*]') }}"	# 单双引号都存在了,就使用了反引号。
      0 14:00:10 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test9.yaml
    
  4. quote:过滤器可以代替引号。

      0 14:08:53 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test10.yaml
    ---
    - hosts: ck-node1
      tasks:
      - shell: echo {{var1 | quote}} >/root/info
        vars:
          var1: "aa\nbb\ncc"
      0 14:08:58 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test10.yaml
    # 带引号的写法与quote作用相同,不带引号识别不了\n换行符,会报错。
      - shell: echo "{{var1}}" >/root/info
    
  5. ternary:实现三元运算的效果,类似if else的功能。

    # 如果变量var1等于Selina,则对应值是Ms,否则是Mr。
      0 14:17:07 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test11.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{ (var1=='selina') | ternary('Ms','Mr') }}"
        vars:
          var1: "selina"
      0 14:17:09 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test11.yaml
    
  6. basename:获取路径字符串的文件名。

      0 14:19:20 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test12.yaml
    ---
    - hosts: ck-node1
      tasks:
      - vars:
          var1: "/server/ops_ansible/variables.yaml"
        debug:
          msg: "{{var1 | basename}}"
      0 14:19:22 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test12.yaml
    
  7. dirname:获取路径字符串的目录路径。

      0 14:20:29 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test13.yaml
    ---
    - hosts: ck-node1
      tasks:
      - vars:
          var1: "/server/ops_ansible/variables.yaml"
        debug:
          msg: "{{var1 | dirname}}"
      0 14:20:31 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test13.yaml
    
  8. realpath:查看软链接所指向的真正文件路径,等于pwd -P。

      0 14:22:15 root@ck-ansible,172.16.2.9:/server/ops_ansible # ln -s /server/ops_ansible/variables.yaml /root/variables.yaml
      0 14:22:19 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test14.yaml
    ---
    - hosts: ck-node1
      tasks:
      - vars:
          var1: "/root/variables.yaml"
        debug:
          msg: "{{var1 | realpath}}"
      0 14:22:23 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test14.yaml
    
  9. relpath:获取指定路径的相对路径。

      0 14:35:12 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test15.yaml
    ---
    - hosts: ck-node1
      tasks:
      - vars:
          var1: "/server/ops_ansible/variables.yaml"
        debug:
          msg: "{{var1 | relpath('/server/ops_tools/ops_scripts')}}"
      0 14:35:15 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test15.yaml
    
  10. splitext:将文件名与后缀名分开。

      0 14:29:19 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test16.yaml
    ---
    - hosts: ck-node1
      tasks:
      - vars:
          var1: "/server/ops_ansible/variables.yaml"
        debug:
          msg: "{{var1 | splitext}}"
      0 14:29:20 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test16.yaml
    # 取文件后缀名。
      0 14:30:36 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test17.yaml
    ---
    - hosts: ck-node1
      tasks:
      - vars:
          var1: "/server/ops_ansible/variables.yaml"
        debug:
          msg: "{{var1 | splitext | last}}"		# 取文件名用first即可。
      0 14:30:38 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test17.yaml
    
  11. bool:判定bool值。

      0 14:46:51 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test18.yaml
    ---
    - hosts: ck-node1
      tasks:
      - vars:
          var1: "1"
        debug:
          msg: "{{var1 | bool}}"
      0 14:46:52 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test18.yaml
    
  12. map:获取数据中每个直接子元素所共有的属性(不能获取嵌套列表的属性),并将值组成一个列表呈现。

      0 14:50:26 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test19.yaml
    ---
    - hosts: ck-node1
      vars:
        users:
        - name: bob
          age: 18
          hobby:
           - swimming
           - runnning
        - name: zoe
          age: 20
          hobby:
           - music
      tasks:
      - debug:
          msg: "{{users | map(attribute='name') | list}}"
      0 14:50:27 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test19.yaml
    # 也可以组成一个字符串,用指定的字符隔开,比如分号。
          msg: "{{users | map(attribute='name') | join(';')}}"
    
  13. to_datetime:计算时间。默认情况下,to_datatime转换的字符串的格式必须是“%Y-%m-%d %H:%M:%S”,如果对应的字符串不是这种格式,则需要在to_datetime中指定与字符串相同的时间格式,才能正确的转换时间类型。

    # 计算时间差1。
      0 14:58:58 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test20.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{ ('2021-10-25 14:55:14' | to_datetime) - ('2021-10-24 15:55:14' | to_datetime) }}"
      0 14:59:00 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test20.yaml
    # 计算时间差2。
      0 15:02:08 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test21.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{ ('20211025' | to_datetime('%Y%m%d')) - ('2021-10-24 15:55:14' | to_datetime) }}"
      0 15:02:08 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test21.yaml
    # 计算两个日期之间一共相差多少秒。
      0 15:05:55 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test22.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{ (('20211025' | to_datetime('%Y%m%d')) - ('20211024' | to_datetime('%Y%m%d'))).total_seconds() }}"
      0 15:05:56 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test22.yaml
    # 计算两个日期之间一共相差多少天。
      0 15:08:30 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test23.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{ (('2021-10-25 14:55:14' | to_datetime) - ('2021-10-20 15:55:14' | to_datetime)).days }}"
      0 15:08:31 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test23.yaml
    
  14. 使用base64编码方式对字符串进行编码解码。

    # 编码
      0 15:12:18 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test24.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{ 'hello' | b64encode }}"
      0 15:12:20 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test24.yaml
    # 解码
      0 15:13:43 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test25.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{ 'aGVsbG8=' | b64decode }}"
      0 15:13:45 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test25.yaml
    
  15. hash:对字符串进行哈希。

    # 使用sha1算法对字符串进行哈希
      0 15:14:52 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test26.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{'123456' | hash('sha1')}}"
    # 使用md5算法对字符串进行哈希。
      0 15:15:19 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test27.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{'123456' | hash('md5')}}"
    
  16. password_hash:对字符串进行哈希,并随机加“盐”,以便

    # 使用sha256算法对字符串进行哈希。
      0 15:24:40 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test28.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{'123456' | password_hash('sha256')}}"
    # 使用sha512算法对字符串进行哈希。
      0 15:25:15 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test29.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{'123456' | password_hash('sha512')}}"
    # 可以使用指定字符串加“盐”
      0 15:37:47 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test30.yaml
    ---
    - hosts: ck-node1
      tasks:
      - debug:
          msg: "{{'123456' | password_hash('sha512','wula')}}"
      0 15:37:50 root@ck-ansible,172.16.2.9:/server/ops_ansible # ansible-playbook test30.yaml
    
  17. dict2items:将字典数据转换处理。

      0 17:05:05 root@ck-ansible,172.16.2.9:/server/ops_ansible # cat test31.yaml
    ---
    - hosts: ck-node1
      vars:
        users:
          bob: male
          zoe: female
      tasks:
      - debug:
          msg: "{{item.key}} is {{item.value}}"
        loop: "{{ users | dict2items }}"
    


写作不易,转载请注明出处,谢谢~~

posted @ 2021-11-04 16:02  merlee  阅读(1692)  评论(0编辑  收藏  举报