ansible取出register變量中最長字符串_台中搬家

台中搬家公司費用怎麼算?

擁有20年純熟搬遷經驗,提供免費估價且流程透明更是5星評價的搬家公司

背景

在用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 }}"

執行測試如下

台中搬家遵守搬運三大原則,讓您的家具不再被破壞!

台中搬家公司推薦超過30年經驗,首選台中大展搬家

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

執行測試如下

總結

  1. shell方式來說,雖然比較繞,但是更加通用;ansible過濾器方式,其中有一個unique的filter,只適用本次場景中正好有重複列表元素的情況,如果每個節點的register取回的字符串完全不一致,則無法適用。

  2. 取回全部register的字符串組合成一個list后,原本計劃使用max過濾器取出列表中最長的字符串元素,發現max過濾器無法傳遞key參數,而python原生的max方法是支持傳遞key參數的。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

台中搬家遵守搬運三大原則,讓您的家具不再被破壞!

台中搬家公司推薦超過30年經驗,首選台中大展搬家