Ansible_kubernetes
Ansible for Kubernetes
Section titled “Ansible for Kubernetes”Overview
Section titled “Overview”Ansible can manage Kubernetes clusters, deploy applications, and handle cluster operations. This guide covers using Ansible with Kubernetes using the community.kubernetes and kubernetes.core collections.
Why Ansible for Kubernetes?
Section titled “Why Ansible for Kubernetes?”- Declarative: Define desired state
- Idempotent: Safe to run multiple times
- Integration: Combine K8s with other infrastructure
- Flexibility: Use Ansible’s full ecosystem
- Existing skills: Leverage Ansible knowledge
Installing Kubernetes Collections
Section titled “Installing Kubernetes Collections”# Install collectionsansible-galaxy collection install community.kubernetesansible-galaxy collection install kubernetes.core
# Install with dependenciesansible-galaxy collection install community.kubernetes kubernetes.coreSetting up K8s Connection
Section titled “Setting up K8s Connection”Using kubeconfig
Section titled “Using kubeconfig”# inventory[kubernetes]k8s-cluster01 ansible_host=k8s.example.com
[kubernetes:vars]ansible_user=adminansible_python_interpreter=/usr/bin/python3kubeconfig_path=~/.kube/configUsing API Token
Section titled “Using API Token”# inventory[kubernetes]k8s-cluster01 ansible_host=k8s.example.com
[kubernetes:vars]ansible_user=adminansible_python_interpreter=/usr/bin/python3kubernetes_api_server: https://k8s.example.com:6443kubernetes_token: <your-service-account-token>Basic Kubernetes Operations
Section titled “Basic Kubernetes Operations”Create Namespace
Section titled “Create Namespace”- name: Create namespace community.kubernetes.k8s: name: myapp kind: namespace state: present
- name: Create namespace with labels community.kubernetes.k8s: name: production kind: namespace state: present labels: environment: production team: platformCreate Deployment
Section titled “Create Deployment”- name: Create Deployment community.kubernetes.k8s: state: present definition: apiVersion: apps/v1 kind: Deployment metadata: name: myapp namespace: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:latest ports: - containerPort: 8080Create Service
Section titled “Create Service”- name: Create Service community.kubernetes.k8s: state: present definition: apiVersion: v1 kind: Service metadata: name: myapp namespace: myapp spec: selector: app: myapp ports: - port: 80 targetPort: 8080 type: ClusterIPUsing K8s Module Options
Section titled “Using K8s Module Options”Wait for Conditions
Section titled “Wait for Conditions”- name: Create pod and wait community.kubernetes.k8s: state: present wait: yes wait_condition: type: Ready status: True definition: apiVersion: v1 kind: Pod metadata: name: myapp spec: containers: - name: app image: myapp:latestMerge Definitions
Section titled “Merge Definitions”- name: Apply with merge community.kubernetes.k8s: state: present merge_type: strategic definition: apiVersion: v1 kind: ConfigMap metadata: name: myapp-config data: config.yaml: | key: valueDelete Resources
Section titled “Delete Resources”- name: Delete namespace community.kubernetes.k8s: state: absent kind: namespace name: myapp
- name: Delete pods community.kubernetes.k8s: state: absent kind: pod namespace: myapp label_selectors: - app=myappManaging Kubernetes Objects
Section titled “Managing Kubernetes Objects”Get Resources
Section titled “Get Resources”- name: Get pods community.kubernetes.k8s_info: kind: Pod namespace: myapp register: pods
- name: Display pod names ansible.builtin.debug: msg: "{{ item.metadata.name }}" loop: "{{ pods.resources | json_query('[*].metadata.name') }}"
- name: Get services community.kubernetes.k8s_info: kind: Service namespace: myappScale Deployment
Section titled “Scale Deployment”- name: Scale deployment community.kubernetes.k8s_scale: name: myapp namespace: myapp replicas: 5 current_replicas: 3Apply Resources
Section titled “Apply Resources”# Use with kubectl-like apply behavior- name: Apply manifest community.kubernetes.k8s: state: present apply: yes definition: "{{ lookup('file', 'manifests/deployment.yaml') | from_yaml }}"Working with Templates
Section titled “Working with Templates”Jinja2 Templates
Section titled “Jinja2 Templates”apiVersion: apps/v1kind: Deploymentmetadata: name: {{ app_name }} namespace: {{ namespace }}spec: replicas: {{ replicas }} selector: matchLabels: app: {{ app_name }} template: metadata: labels: app: {{ app_name }} spec: containers: - name: {{ app_name }} image: {{ image }}:{{ image_tag }} ports: - containerPort: {{ port }}- name: Deploy application hosts: localhost gather_facts: no vars: app_name: myapp namespace: production replicas: 3 image: myapp image_tag: latest port: 8080
tasks: - name: Template deployment ansible.builtin.template: src: templates/deployment.yaml.j2 dest: /tmp/deployment.yaml
- name: Apply deployment community.kubernetes.k8s: state: present definition: "{{ lookup('file', '/tmp/deployment.yaml') | from_yaml }}"Helm Integration
Section titled “Helm Integration”Install Helm Chart
Section titled “Install Helm Chart”- name: Install Helm chart community.kubernetes.helm: name: myapp chart_ref: bitnami/nginx namespace: myapp values: service: type: LoadBalancer release_state: presentManage Helm Releases
Section titled “Manage Helm Releases”- name: Upgrade Helm release community.kubernetes.helm: name: myapp chart_ref: bitnami/nginx namespace: myapp values: service: type: NodePort release_state: present
- name: Uninstall Helm release community.kubernetes.helm: name: oldapp release_state: absentKubernetes Operator Pattern
Section titled “Kubernetes Operator Pattern”Operator-like Playbook
Section titled “Operator-like Playbook”- name: Ensure application is running hosts: localhost gather_facts: no tasks: - name: Get current state community.kubernetes.k8s_info: kind: Deployment name: myapp namespace: myapp register: current_deploy
- name: Scale if needed community.kubernetes.k8s_scale: name: myapp namespace: myapp replicas: "{{ desired_replicas }}" when: - current_deploy.resources | length > 0 - current_deploy.resources[0].spec.replicas | int != desired_replicasCI/CD Integration
Section titled “CI/CD Integration”GitHub Actions
Section titled “GitHub Actions”name: Deploy to Kubernetes
on: push: branches: [main]
jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
- name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.9'
- name: Install Ansible run: | pip install ansible ansible-galaxy collection install community.kubernetes kubernetes.core
- name: Deploy to Kubernetes run: | ansible-playbook deploy.yml env: KUBE_TOKEN: ${{ secrets.KUBE_TOKEN }}Playbook for CI/CD
Section titled “Playbook for CI/CD”- name: Deploy application hosts: localhost gather_facts: no vars: app_version: "{{ lookup('env', 'APP_VERSION') }}" namespace: production
tasks: - name: Create namespace community.kubernetes.k8s: name: "{{ namespace }}" kind: namespace state: present
- name: Deploy ConfigMap community.kubernetes.k8s: state: present definition: apiVersion: v1 kind: ConfigMap metadata: name: app-config namespace: "{{ namespace }}" data: VERSION: "{{ app_version }}"
- name: Deploy application community.kubernetes.k8s: state: present definition: "{{ lookup('file', 'k8s/deployment.yaml') | from_yaml_all | first }}" vars: image_tag: "{{ app_version }}"Best Practices
Section titled “Best Practices”1. Use Namespaces
Section titled “1. Use Namespaces”# Always specify namespace- name: Create resource community.kubernetes.k8s: name: myapp namespace: mynamespace kind: Deployment2. Wait for Resources
Section titled “2. Wait for Resources”# Wait for rollout- name: Deploy and wait community.kubernetes.k8s: state: present wait: yes wait_timeout: 300 definition: "{{ deployment_manifest }}"3. Use Dynamic Inventory
Section titled “3. Use Dynamic Inventory”plugin: community.kubernetes.k8sconnections: - namespaces: - production4. Handle Secrets
Section titled “4. Handle Secrets”# Use Kubernetes secrets- name: Create secret community.kubernetes.k8s: state: present definition: apiVersion: v1 kind: Secret metadata: name: db-credentials type: Opaque stringData: username: admin password: "{{ db_password }}"Summary
Section titled “Summary”Ansible for Kubernetes enables:
- Application deployment: Deploy to K8s from Ansible
- Cluster management: Manage K8s resources
- Helm integration: Manage Helm releases
- CI/CD: Automate deployments
- Operator patterns: Implement operator-like behavior
Key collections:
- community.kubernetes: Core K8s modules
- kubernetes.core: Additional K8s modules
- community.general: Helper modules