I had to install kubectl via ansible and I spent some time to create an Ansible script following the official Kubectl linux installation instruction

This is working for me both using Ansible via command line and using Packer tool to create AWS AMIs:

---

- name: Get latest kubectl version
  uri:
    url: https://dl.k8s.io/release/stable.txt
    return_content: yes
  register: version

- name: create kubectl versioned directory
  file:
    path: /opt/kubectl-{{ version.content }}
    state: directory
  become: true

- name: Download the latest kubectl release
  uri:
    url: https://dl.k8s.io/release/{{ version.content }}/bin/linux/amd64/kubectl
    dest: /opt/kubectl-{{ version.content }}
  register: kubectl
  become: true

- name: Download the kubectl checksum
  uri:
    url: https://dl.k8s.io/release/{{ version.content }}/bin/linux/amd64/kubectl.sha256
    dest: /opt/kubectl-{{ version.content }}
  register: kubectl
  become: true

- name: Get kubectl sha256sum
  shell: sha256sum /opt/kubectl-{{ version.content }}/kubectl | cut -d " " -f1
  register: file_shasum

- set_fact:
    shasum1={{ file_shasum.stdout }}

- debug: var=shasum1
  run_once: true

- name: get sha256sum value from file
  command: cat /opt/kubectl-{{ version.content }}/kubectl.sha256
  register: downloaded_shasum

- set_fact:
    shasum2={{ downloaded_shasum.stdout }}

- debug: var=shasum2
  run_once: true

- name: Assert that the kubectl binary is OK
  assert:
    that:
      - file_shasum.stdout == downloaded_shasum.stdout
    fail_msg: "Shasum does not correspond"
    success_msg: "kubectl shasum verified: ok"

- name: Change kubectl file permission
  file:
    path: "/opt/kubectl-{{ version.content }}/kubectl"
    mode: '0755'
  become: true

- name: create a symlink to kubectl
  file:
    src: "/opt/kubectl-{{ version.content }}/kubectl"
    dest: "/usr/bin/kubectl"
    state: link
  become: true

Any comment appreciated.

Answer from Daniele Scarano on Stack Overflow
🌐
GitHub
github.com › githubixx › ansible-role-kubectl
GitHub - githubixx/ansible-role-kubectl: Installs kubectl command line utility used to interact with the Kubernetes API Server · GitHub
Via ansible-galaxy command and download directly from Ansible Galaxy: ansible-galaxy install role githubixx.kubectl
Starred by 19 users
Forked by 17 users
Top answer
1 of 5
4

I had to install kubectl via ansible and I spent some time to create an Ansible script following the official Kubectl linux installation instruction

This is working for me both using Ansible via command line and using Packer tool to create AWS AMIs:

---

- name: Get latest kubectl version
  uri:
    url: https://dl.k8s.io/release/stable.txt
    return_content: yes
  register: version

- name: create kubectl versioned directory
  file:
    path: /opt/kubectl-{{ version.content }}
    state: directory
  become: true

- name: Download the latest kubectl release
  uri:
    url: https://dl.k8s.io/release/{{ version.content }}/bin/linux/amd64/kubectl
    dest: /opt/kubectl-{{ version.content }}
  register: kubectl
  become: true

- name: Download the kubectl checksum
  uri:
    url: https://dl.k8s.io/release/{{ version.content }}/bin/linux/amd64/kubectl.sha256
    dest: /opt/kubectl-{{ version.content }}
  register: kubectl
  become: true

- name: Get kubectl sha256sum
  shell: sha256sum /opt/kubectl-{{ version.content }}/kubectl | cut -d " " -f1
  register: file_shasum

- set_fact:
    shasum1={{ file_shasum.stdout }}

- debug: var=shasum1
  run_once: true

- name: get sha256sum value from file
  command: cat /opt/kubectl-{{ version.content }}/kubectl.sha256
  register: downloaded_shasum

- set_fact:
    shasum2={{ downloaded_shasum.stdout }}

- debug: var=shasum2
  run_once: true

- name: Assert that the kubectl binary is OK
  assert:
    that:
      - file_shasum.stdout == downloaded_shasum.stdout
    fail_msg: "Shasum does not correspond"
    success_msg: "kubectl shasum verified: ok"

- name: Change kubectl file permission
  file:
    path: "/opt/kubectl-{{ version.content }}/kubectl"
    mode: '0755'
  become: true

- name: create a symlink to kubectl
  file:
    src: "/opt/kubectl-{{ version.content }}/kubectl"
    dest: "/usr/bin/kubectl"
    state: link
  become: true

Any comment appreciated.

2 of 5
1

You're on the right track. We install Rundeck, which follows similar steps, using the following Ansible code:

- name: add rundeck apt repository key
  become: true
  apt_key:
    url: https://bintray.com/user/downloadSubjectPublicKey?username=bintray

- name: add rundeck apt repository
  become: true
  apt_repository:
    repo: 'deb https://rundeck.bintray.com/rundeck-deb /'
    filename: rundeck

- name: install rundeck dependencies
  become: true
  apt:
    name: openjdk-8-jdk

- name: install rundeck and rundeck-cli
  become: true
  apt:
    name: "{{ item }}"
  loop:
    - rundeck
    - rundeck-cli

Use that as an example and you should be good to go. The apt_repository module runs apt-get update automatically when new repositories are added.

Discussions

kubernetes - how to run cmd kubectl apply using Ansible properly - Stack Overflow
I'm trying to automate the following: Apply the Physical Volumes kubectl apply -f food-pv.yaml kubectl apply -f bar-pv.yaml Apply the Physical Volume Claims kubectl apply -f foo.yaml kubectl app... More on stackoverflow.com
🌐 stackoverflow.com
How to setup ansible playbook that is able to execute kubectl (kubernetes) commands - Stack Overflow
Find centralized, trusted content ... you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm trying to write simple ansible playbook that would be able to execute some arbitrary command against the pod (container) running in kubernetes cluster. I would like to utilise kubectl connection ... More on stackoverflow.com
🌐 stackoverflow.com
Error setting up kubernetes cluster
There are a few things you need to do to configure a Linux machine to run Kubernetes. Did you follow a blog, guide, etc.? The error essentially says, "containerd is not running." Is containerd running? Try going back through your instructions and check your work. When it comes to the containerd config.toml we use the default configuration, but set SystemdCgroup=true because Linux is using systemd for init. Kubernetes 1.26.1 should default to systemd for Cgroup. Kubernetes must use the same Cgroup setting as containerd in order for kubelet to start. Is kubelet running? More on reddit.com
🌐 r/kubernetes
15
1
January 21, 2023
Ansible and Kubectl Commands
You can use the k8s module: https://docs.ansible.com/ansible/latest/collections/kubernetes/core/k8s_module.html Then use filters to get the part you want: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html And use set_fact to save it to a variable to be used in your playbooks: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html More on reddit.com
🌐 r/kubernetes
9
2
September 6, 2022
🌐
Ansible
docs.ansible.com › projects › ansible › latest › collections › kubernetes › core › kubectl_connection.html
kubernetes.core.kubectl connection – Execute tasks in pods running on Kubernetes. — Ansible Community Documentation
To install it, use: ansible-galaxy collection install kubernetes.core. You need further requirements to be able to use this connection plugin, see Requirements for details. To use it in a playbook, specify: kubernetes.core.kubectl.
🌐
Hewlett Packard
hewlettpackard.github.io › Docker-Synergy › post-deploy › install-kubectl.html
Installing kubectl | HPE Enterprise Containers
A convenience playbook is provided to make it easy to install kubectl on the Ansible controller. This playbook uses variables in group_vars/all/vars to determine which version to download. The default version specified by the variable kubectl_version in the sample variables file is 1.11.5.
🌐
GitHub
gist.github.com › allanger › 84db2647578316f8e721f7219052788f
Deploy Kubernetes with Ansible · GitHub
- name: Install kubectl. package: name: kubectl state: present when: node_type == 'master' Create a file, for example hosts.yaml (you should read about ansible inventory files for better understanding) # -------------------------------------- # -- Inventory file example # -- This is gonna be two-nodes cluster # -------------------------------------- --- k8s_master: hosts: ${MASTER_NODE_ADDRESS} vars: node_type: "master" ansible_user...
🌐
Spacelift
spacelift.io › blog › ansible-kubernetes
How to Manage Kubernetes with Ansible [Tutorial]
October 10, 2025 - sudo apt update && sudo apt upgrade –y sudo apt install python3-pip #Download Kubernetes Tools using Curl: curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" #Verify Checksum (Response ...
Find elsewhere
🌐
Linux sysadmins
linuxsysadmins.com › install-kubernetes-cluster-with-ansible
Install Kubernetes Cluster with Ansible on Ubuntu in 5 minutes
March 7, 2022 - lineinfile: dest: /etc/fstab regexp: ... - name: Installing Kubernetes Cluster Packages. apt: name: - kubeadm - kubectl - kubelet state: present - name: Enable service kubelet, and enable persistently service: name: kubelet enabled: yes - name: ...
🌐
Medium
medium.com › @mucahitkumlay › kubernetes-install-with-ansible-7dbd958584e5
Kubernetes install with Ansible. What is the Ansible ? | by Mücahit Kumlay | Medium
November 2, 2021 - vim kubernetes.yml ## Add this- ... /etc/yum.repos.d/kubernetes.repo - name: Install kubelet kubeadm kubectl shell: | sudo yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes - name: Start and enable service: name: ...
🌐
Ansible Galaxy
galaxy.ansible.com › codecap › kubectl
codecap.kubectl - Ansible Galaxy
Jump start your automation project with great content from the Ansible community
🌐
buildVirtual
buildvirtual.net › home › devops › deploy a kubernetes cluster using ansible
Deploy a Kubernetes Cluster using Ansible - buildVirtual
July 12, 2021 - How to Deploy a Kubernetes Cluster using Ansible Playbooks. Learn how to install Kubernetes, initialise a new Kubernetes cluster and configure worker nodes
🌐
Kubernetes
kubernetes.io › blog › 2019 › 03 › 15 › kubernetes-setup-using-ansible-and-vagrant
Kubernetes Setup Using Ansible and Vagrant | Kubernetes
January 3, 2026 - Installation binaries can be found here. Oracle VirtualBox can be used as a Vagrant provider or make use of similar providers as described in Vagrant's official documentation. Ansible should be installed in your machine.
🌐
Medium
medium.com › @venkataramarao.n › kubernetes-setup-using-ansible-script-8dd6607745f6
Kubernetes setup using Ansible script | by Venkata RamaRao Nibhanupudi | Medium
May 2, 2024 - 1. Create an Ansible playbook: Create an Ansible playbook (e.g., kubernetes-cluster.yml) that defines the tasks to set up your Kubernetes cluster. Here's a basic playbook: --- - hosts: master become: yes tasks: - name: Install Docker apt: name: ...
🌐
Ansible
docs.ansible.com › ansible › 2.9 › plugins › connection › kubectl.html
kubectl – Execute tasks in pods running on Kubernetes — Ansible Documentation
Please upgrade to a maintained version. See the latest Ansible community documentation . For Red Hat customers, see the Red Hat AAP platform lifecycle. New in version 2.5. ... Use the kubectl exec command to run tasks in, or put/fetch files to, pods running on the Kubernetes container platform.
Top answer
1 of 4
1

I would like to utilise kubectl connection plugin: https://docs.ansible.com/ansible/latest/plugins/connection/kubectl.html but having struggle to figure out how to actually do that.

The fine manual describes how one uses connection plugins, and while it is possible to use in in tasks, that is unlikely to make any sense unless your inventory started with Pods.

The way I have seen that connection used is to start by identifying the Pods against which you might want to take action, and then run a playbook against a unique group for that purpose:

- hosts: all
  tasks:
  - set_fact:
      # this is *just an example for brevity*
      # in reality you would use `k8s:` or `kubectl get -o name pods -l my-selector=my-value` to get the pod names
      pod_names:
      - nginx-12345
      - nginx-3456
  - add_host:
      name: '{{ item }}'
      groups:
      - my-pods
    with_items: '{{ pod_names }}'

- hosts: my-pods
  connection: kubectl
  tasks:
  # and now you are off to the races
  - command: ps -ef
  # watch out if the Pod doesn't have a working python installed
  # as you will have to use raw: instead
  # (and, of course, disable "gather_facts: no")
  - raw: ps -ef
2 of 4
1

First install k8s collections

ansible-galaxy collection install community.kubernetes

and here is play-book, it will sort all pods and run a command in every pod

---
- 
  hosts: localhost

  vars_files: 
    - vars/main.yaml 

  collections:
    - community.kubernetes    

  tasks:     
    -
      name: Get the pods in the specific namespace
      k8s_info:
        kubeconfig: '{{ k8s_kubeconfig }}'
        kind: Pod
        namespace: test
      register: pod_list


    - 
      name: Print pod names
      debug:
         msg: "pod_list: {{ pod_list | json_query('resources[*].status.podIP')  }} "

    - set_fact:
        pod_names: "{{pod_list|json_query('resources[*].metadata.name')}}"

    - 
      k8s_exec:
        kubeconfig: '{{ k8s_kubeconfig }}'
        namespace: "{{ namespace  }}"
        pod: "{{ item.metadata.name }}"
        command: apt update
      with_items: "{{ pod_list.resources }}"
      register: exec
      loop_control:
        label: "{{ item.metadata.name }}"
🌐
GitHub
github.com › torgeirl › kubernetes-playbooks
GitHub - torgeirl/kubernetes-playbooks: Ansible playbooks for setting up a Kubernetes cluster · GitHub
Ansible and Python3 installed on the local machine (# yum install ansible).
Starred by 107 users
Forked by 66 users
Languages   HCL
🌐
OneUptime
oneuptime.com › home › blog › how to install kubectl with ansible
How to Install kubectl with Ansible
February 21, 2026 - You need to upgrade kubectl across all machines when you upgrade your cluster · Some machines run Ubuntu, others run CentOS, and a few run macOS · Ansible handles all of these cases from a single playbook. The most portable method downloads the official binary directly from Google: # install_kubectl_binary.yml - Install kubectl from official binary release --- - name: Install kubectl from Official Binary hosts: all become: true vars: kubectl_version: "1.29.2" kubectl_install_dir: /usr/local/bin tasks: - name: Determine architecture ansible.builtin.set_fact: kubectl_arch: "{{ 'arm64' if ansib
🌐
Ansible
docs.ansible.com › projects › ansible › latest › collections › kubernetes › core › docsite › kubernetes_scenarios › k8s_intro.html
Introduction to Ansible for Kubernetes — Ansible Community Documentation
Kubernetes Python client installed on the host that will execute the modules. The Kubernetes modules are part of the Ansible Kubernetes collection. ... By default the Kubernetes Rest Client will look for ~/.kube/config, and if found, connect using the active context. You can override the location of the file using the kubeconfig parameter, and the context, using the context parameter. Basic authentication is also supported using the username and password options.