ansible取出register变量中最长字符串
manongba · 376浏览 · 发布于2020-06-04
背景
在用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 }}"
执行测试如下
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
执行测试如下
总结
shell方式来说,虽然比较绕,但是更加通用;ansible过滤器方式,其中有一个unique的filter,只适用本次场景中正好有重复列表元素的情况,如果每个节点的register取回的字符串完全不一致,则无法适用。
取回全部register的字符串组合成一个list后,原本计划使用max过滤器取出列表中最长的字符串元素,发现max过滤器无法传递key参数,而python原生的max方法是支持传递key参数的。
分类: ansible
相关推荐
Linux操作系统启动流程
qq2360248666 · 1144浏览 · 2019-06-13 09:31:05
详解全链路监控架构--目标、功能模块、Dapper和方案比较
qq2360248666 · 1353浏览 · 2019-06-27 11:28:13
手机最后1%的电量到底能用多久?
manongba · 794浏览 · 2019-09-09 16:02:58
周杰伦新歌《说好不哭》在线无损试听播放带TXT,lrc歌词
qq2360248666 · 4687浏览 · 2019-09-20 14:14:55
周杰伦新歌《我是如此相信》在线无损试听播放带TXT,lrc歌词
kenrry1992 · 1265浏览 · 2019-12-16 10:48:34
分类专栏
最新发布
最热排行
0评论