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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值