如何从kubernetes集群的ansible(寄存器stdout)初始化中获取最后两行

hsvhsicv  于 2022-11-02  发布在  Kubernetes
关注(0)|答案(3)|浏览(132)

这是我的剧本文件的一部分,问题:

- name: Initialize the Kubernetes cluster using kubeadm
    command: kubeadm init --config /etc/kubernetes/kubeadminit.yaml
    register: init_output

  - name: Copy join command to local file
    local_action: copy content={{ init_output.stdout }} dest="./join-command"

当前join-command包含整个标准输出(30多行文本)。我想获取的只是init_output.stdout的最后两行,而不是整个输出。我已经研究过使用索引引用(即init_output.stdout[#]),但我不知道输出是否总是相同的长度,也不知道如何使用索引来获取多行,但我很确定最后两行永远是join命令,有什么建议吗?

gcmastyq

gcmastyq1#

从列表中选择最后2行stdout_lines

- local_action: copy content={{ init_output.stdout_lines[-2:] }} dest="./join-command"

可以格式化块中的行。例如

- local_action:
        module: copy
        content: |
          {{ init_output.stdout_lines[-2] }}
          {{ init_output.stdout_lines[-1] }}
        dest: "./join-command"

要在循环中追加行,请尝试

- local_action:
        module: lineinfile
        path: "./join-command"
        line: "{{ item }}"
        insertafter: EOF
        create: true
      loop: "{{ init_output.stdout_lines[-2:] }}"
7gyucuyw

7gyucuyw2#

我遇到了这类问题,不想将join命令复制到本地文件,所以我用set_fact代替了它:

- set_fact:
    join_cmd: '{{ init_output.stdout_lines[-2][:-2] }}{{ init_output.stdout_lines[-1] }}'
wj8zmpe1

wj8zmpe13#

我做了这个...

- name: kubeadm init
  shell: |
    kubeadm init --control-plane-endpoint \
    localhost \
    --control-plane-endpoint kube-api.local >> /tmp/run_kube_init.sh
  when: master == "yes"

- name: Get join from master
  fetch:
    src: "/tmp/run_kube_init.sh"
    dest: "/tmp/run_kube_init.sh"
    flat: yes
  when: ansible_hostname == 'k-master'

- name: Add join file to nodes
  copy:
    src: "/tmp/run_kube_init.sh"
    dest: "/tmp/run_kube_init.sh"
  when: master == "no"

- name: Extract join token for nodes
  shell: tail -n +2 /tmp/run_kube_init.sh | head -n -1 | awk '{print $5}' | tail -n 1
  register: JOIN_TOKEN

- set_fact:
    join_token: "{{ JOIN_TOKEN.stdout }}"

- name: join nodes
  shell: |
    kubeadm join kube-api.local:6443 \
    --token {{ JOIN_TOKEN.stdout }} \
    --discovery-token-unsafe-skip-ca-verification
  when: master == "no"

- name: rm /tmp/run_kube_init.sh
  ansible.builtin.file:
    path: /tmp/run_kube_init.sh
    state: absent

相关问题