Home Managing Kubernetes with Ansible
Post
Cancel

Managing Kubernetes with Ansible

Overview

While Kubernetes is a powerful platform, management of the platform can be challenging especially as the number of clusters increase. There are a variety of tools help manage this. Ansible is a well known open source tool in the configuration management space. This post will go over how to get started in using Kubernetes with Ansible.

Dependencies

Server Side (Ansible server)

Ansible Galaxy Package

1
ansible-galaxy collection install kubernetes.core

Install pip3

1
sudo apt install python3-pip
1
pip3 install kubernetes

As explained in this Ansible documentation the ansible python interpreter does detect and automatically use Python 3 on many platforms. However, for those that do not, use the following ways to explicitly configure it.

If you see some output similar to this when you run a playbook:

1
2
3
TASK [Get Cluster information] ************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ImportError: No module named kubernetes.dynamic
fatal: [[email protected]]: FAILED! => {"changed": false, "error": "No module named kubernetes.dynamic", "msg": "Failed to import the required Python library (kubernetes) on c1-master1's Python /usr/bin/python. Please read the module documentation and install it in the appropriate location. If the required library is installed, but Ansible is using the wrong Python interpreter, please consult the documentation on ansible_python_interpreter"} 

You will know you need to configure either of the following:

1
2
3
4
5
6
7
8
9
10
# Example inventory that makes an alias for localhost that uses Python3
localhost-py3 ansible_host=localhost ansible_connection=local ansible_python_interpreter=/usr/bin/python3

# Example of setting a group of hosts to use Python3
[py3_hosts]
ubuntu16
fedora27

[py3_hosts:vars]
ansible_python_interpreter=/usr/bin/python3
1
2
# ansible localhost-py3 -m ping
# ansible-playbook sample-playbook.yml

Add the “-e ‘ansible_python_interpreter=/usr/bin/python3’” flag at the end of the command

1
2
ansible localhost -m ping -e 'ansible_python_interpreter=/usr/bin/python3'
ansible-playbook sample-playbook.yml -e 'ansible_python_interpreter=/usr/bin/python3'

Client Side (Management node)

Install pip3

1
sudo apt install python3-pip
1
pip3 install kubernetes

Running Playbooks

From the same directory in which the playbook resides:

1
ansible-playbook playbook.yml

Running on a group defined in your hosts.ini file

1
ansible-playbook playbook.yml --limit groupname

If you want to see a list of hosts affected by your playbook before you actually run it, use –list-hosts

1
ansible-playbook playbook.yml --list-hosts

Sample Playbook

1
This post is licensed under CC BY 4.0 by the author.