Skip to content

Instantly share code, notes, and snippets.

@blachniet
Created August 12, 2023 13:13
Show Gist options
  • Save blachniet/38fbf026e06804e2e71c14595c6d7d68 to your computer and use it in GitHub Desktop.
Save blachniet/38fbf026e06804e2e71c14595c6d7d68 to your computer and use it in GitHub Desktop.
Execute command in Kubernetes Deployment with Ansible
---
# This playbook queries Kubernetes to find a pod within a playbook and then
# runs a commnad within one of those pods. This is essentially the Ansible
# way to perform the following kubectl command:
#
# kubectl exec -n keycloak deploy/postgres -- psql -U postgres -c '\l'
#
- hosts: localhost
tasks:
- name: Get the Postgres deployment
kubernetes.core.k8s_info:
kind: Deployment
namespace: keycloak
name: postgres
register: postgres_deploy
failed_when: postgres_deploy.resources | length != 1
- name: Get the pods in the Postgres deployment using the selector from the
deployment
kubernetes.core.k8s_info:
kind: Pod
namespace: keycloak
label_selectors: '{{ postgres_deploy.resources[0].spec.selector.matchLabels | list }}'
register: postgres_pods
failed_when: postgres_pods.resources | length != 1
- name: Print the postgres pod names
ansible.builtin.debug:
var: postgres_pods.resources | map(attribute='metadata.name')
- name: Execute a command in one of the pods
kubernetes.core.k8s_exec:
namespace: keycloak
pod: '{{ postgres_pods.resources[0].metadata.name }}'
command: psql -U postgres -c '\l'
register: cmd_result
- name: Print the command output
ansible.builtin.debug:
var: cmd_result.stdout_lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment