How to grab last two lines from ansible (register stdout) initialization of kubernetes cluster

1/16/2020

This is the piece of my playbook file for the question:

  - 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"

Currently join-command contains the entire stdout (30+ lines of text) for content. What I want to grab is just the last two lines of init_output.stdout instead of the entire output. I've looked into using index reference (ie. init_output.stdout[#]) but I don't know that the output will always be the same length and I don't know how to use indexes to grab more than one line, but i'm fairly certain that the last two lines will always be the join command. Any suggestions?

-- Levi Silvertab
ansible
kubernetes

1 Answer

1/16/2020

Select last 2 lines from the list stdout_lines

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

It's possible to format the lines in a block. For example

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

To append the lines in a loop try

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