Removing DeploymentConfig when Pods are of a certain age using Ansible

6/4/2020

I'm using Ansible to rollout a DeploymentConfig and all its sub components like Service, Route and PersistentVolumeClaim on a Kubernetes Cluster on Openshift.

Now I'd like to remove all these components from the cluster if Pods are of a certain age. How would I do this with Ansible? I know there's a module called k8s_info, but how do I query the Pods and use the result to set the status of all items to absent.

Setup of my Play so far:

---
- name: Remove old deployments
  module_defaults:
    k8s:
      validate_certs: no
  hosts: localhost
  tasks:
    - name: Get a list of all service objects
      k8s_info:
        api_version: v1
        kind: Pod
        namespace: "{{ PROJECT }}"
        field_selectors:
          - status.phase=Running
          # filter on pods older than 5 days
      register: podlist
# use podlist to get metadata names for which to set state to absent
-- Dormouse
ansible
kubernetes
openshift

1 Answer

6/10/2020

There must be a cleaner/easier approach but here is a workable alternative : You can create a job along with your resources, which keeps track of the age of the pod and delete all the resources along with itself when time comes (condition met). The job should run with a service account that has access to do so.

-- Soumyadeep Paul
Source: StackOverflow