Get the App
SLTechnology News&Howtos  ›  Servers  › 

Use Ansible to manage Kubernetes resources

Shulou Source: shulou.com Published: 2022-06-02 14:17:51 10月01日 Update

Two days ago, an article entitled "Think twice before using Helm" caught everyone's attention. The author explains Helm's problems from authentication, life cycle management, error handling and other aspects. I basically agree with the author. In most cases we just use helm as a template engine, generating charts into formats that Kubernetes can handle. But from a usage perspective, this template implementation is too heavy. Interested parties can read the original.

So if Helm isn't light and easy to use, what other options do we have?

Ansible, as a deployment management tool, is being sought after by more and more O & M personnel. It supports Jinja2 template engine, and is agentless node architecture, very convenient to do some template work. So this article describes how to manage Kubernetes resources using Ansible.

Use Ansible first to avoid using its modules. Kubernetes-related modules can be found in [2]. There are five modules: k8s, k8s_facts, k8s_scale, kubernetes and oc. Kubernetes and oc modules have been abandoned in ansible 2.6 because the implementation logic is not easy to use. It is recommended to use the first three. k8s_scale from ansible 2.5, k8s from ansible 2.6, k8s_facts from ansible 2.7. To use these three modules, you also need to install the Python package for openshift. The following code is all based on version 2.7 of ansible.

I. K8S module

To manage Kubernetes resources, use the k8s module. The following is how to create a namespace.

name: Create a k8s namespace

k8s:

name: testing

api_version: v1

kind: Namespace

state: present

If you want to create a Service, you can also use the following code:

name: Create a Service object from an inline definition

k8s:

state: present

definition:

apiVersion: v1

kind: Service

metadata:

name: web

namespace: testing

labels:

app: galaxy

service: web

spec:

selector:

app: galaxy

service: web

ports:protocol: TCP

targetPort: 8000

name: port-8000-tcp

port: 8000

You can see that definition is written in the native Kubernetes, and the parameters of the k8s module are also written less, so it will be quick to get started.

If k8s module and ansible lookup plug-in are used together, you can write more concise code, as follows

#tasks.yml

name: Create a Service object from an external file

var:

name: "web"

k8s:

state: present

definition:

{{ lookup('template', '/path/to/service.yml') | to_yaml(indent=6) }}

#/path/to/service.yml

apiVersion: v1

kind: Service

metadata:

name: {{ name }} #

Tags: Module resource management template writing file angle work example function command namely format community or processing brevity three code author Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Linux Xiaomi MariaDB OPPO Reno