ansible kubernetes - ghdrako/doc_snipets GitHub Wiki

Ansible Kubernetes Modules

Ansible offers various modules to interact with Kubernetes resources, including:

  • k8s: General-purpose module to manage Kubernetes resources.
  • k8s_info: Retrieves information about Kubernetes resources.

Kubernetes Inventory Plugin

Ansible also provides an inventory plugin to dynamically retrieve information about Kubernetes resources, enabling you to target specific nodes, pods, or other resources.

Deploying an Application

---
- name: Deploy NGINX application on Kubernetes
hosts: localhost
tasks:
 - name: Create deployment
k8s:
kubeconfig: /path/to/kubeconfig
state: present
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
 image: nginx:1.16
ports:
- containerPort: 80

Managing Configurations (ConfigMap)

---
- name: Manage ConfigMap
hosts: localhost
tasks:
- name: Create ConfigMap
k8s:
kubeconfig: /path/to/kubeconfig
state: present
definition:
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
namespace: default
data:
app.properties: |
key=value

Scaling Resources (Horizontal Pod Autoscaler)

---
- name: Create Horizontal Pod Autoscaler
hosts: localhost
tasks:
- name: Apply HPA
k8s:
kubeconfig: /path/to/kubeconfig
state: present
definition:
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
name: nginx-hpa
namespace: default
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx-deployment
minReplicas: 1
maxReplicas: 10
 metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50