本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
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 }}"

执行测试如下

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

分类: ansible

加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页