ansible取出register变量中最长字符串

背景

在用ansible撰写一个etcd恢复的playbook时,有一个操作是获取etcd启动时的"initial-cluster"启动参数,该参数在etcd集群不同节点不一致,需要取出etcd节点启动参数中最长的作为etcdctl snapshot restore的参数。

[root@tke-init ansible]# cat etcd.hosts 
[etcd]
10.0.32.79
10.0.32.41
10.0.32.97

[snapshot]
10.0.32.79 recoverySnapFile=/alauda/etcd_bak/snap-202005250843.db

[root@tke-init ansible]# cat c.yaml 
---
- name: etcd snapshot recovery
  gather_facts: false
  hosts: all
  tasks:
  - name: get the initial-cluster info
    shell: |+
      cat /etc/kubernetes/manifests/etcd.yaml |grep "initial-cluster="|sed 's/.*initial-cluster=//'
    register: initialCluster

  - debug:
      msg: "{{initialCluster.stdout}}"

如下图,需要取出圈出的最长的字符串。

实现

shell方式

[root@tke-init ansible]# cat c.yaml 
---
- name: etcd snapshot recovery
  gather_facts: false
  hosts: all
  tasks:
  - name: get the initial-cluster info
    shell: |+
      cat /etc/kubernetes/manifests/etcd.yaml |grep "initial-cluster="|sed 's/.*initial-cluster=//'
    register: initialCluster

  - debug:
      msg: "{{initialCluster.stdout}}"
  
  - name: if the /tmp/a.txt exist,remove it 
    file:
      path: /tmp/a.txt
      state: absent
      force: yes
    run_once: true
    delegate_to: localhost 

  - name: echo the all initialCluster parameter to localhost
    shell: |+
      echo "{{item}}" >>/tmp/a.txt
    with_items:
      - "{{ initialCluster.stdout }}"
    delegate_to: localhost

  - name: get the longest initial-cluster paramaters
    shell:
      cat /tmp/a.txt  |awk '{print length($0),$0}'|sort -k1 -rn|head -1|awk '{print $2}'
    register: maxInitialCluster
    run_once: true
    delegate_to: localhost
  - debug:
      msg: "{{ maxInitialCluster.stdout }}"

执行测试如下

image-20200602071324775

ansible过滤器方式

[root@tke-init ansible]# cat bb.yaml 
---
- name: test
  gather_facts: false
  hosts: all
  tasks:
  - name: get the initial-cluster info
    shell: |+
      cat /etc/kubernetes/manifests/etcd.yaml |grep "initial-cluster="|sed 's/.*initial-cluster=//'
    register: initialCluster

  - set_fact:
       combined_initialCluster: "{{ groups['etcd'] |map('extract',hostvars,['initialCluster','stdout']) |list |join(',')  }}"

  - set_fact:
      final_initialCluster: "{{ combined_initialCluster.split(',')|unique|join(',') }}"

  - debug:
      var: final_initialCluster

执行测试如下

image-20200603205659615

总结

  1. shell方式来说,虽然比较绕,但是更加通用;ansible过滤器方式,其中有一个unique的filter,只适用本次场景中正好有重复列表元素的情况,如果每个节点的register取回的字符串完全不一致,则无法适用。

  2. 取回全部register的字符串组合成一个list后,原本计划使用max过滤器取出列表中最长的字符串元素,发现max过滤器无法传递key参数,而python原生的max方法是支持传递key参数的。

    image-20200603211020953

image-20200603211209293

posted @ 2020-06-03 23:04  360linux  阅读(309)  评论(0编辑  收藏  举报