Home > Blockchain >  how to run cmd kubectl apply using Ansible properly
how to run cmd kubectl apply using Ansible properly

Time:01-07

I'm trying to automate the following:

  1. Apply the Physical Volumes
    • kubectl apply -f food-pv.yaml
    • kubectl apply -f bar-pv.yaml
  2. Apply the Physical Volume Claims
    • kubectl apply -f foo.yaml
    • kubectl apply -f bar.yaml
  3. Apply the Services
    • kubectl apply -f this-service.yaml
    • kubectl apply -f that-nodeport.yaml
  4. Apply the Deployment
    • kubectl apply -f something.yaml

Now I could run the cmds as shell commands, but I don't think that's the proper way to do it. I've been reading thru the Ansible documentation, but I'm not seeing what I need to do for this. Is there a better way to apply these yaml files without using a series of shell cmds?

Thanks in advance

CodePudding user response:

Best way would be to use ansible kubernetes.core collection https://github.com/ansible-collections/kubernetes.core

An example with file:

    - name: Create a Deployment by reading the definition from a local file
  kubernetes.core.k8s:
    state: present
    src: /testing/deployment.yml

So, you could loop from different folders containing the yaml definitions for your objects with state: present

CodePudding user response:

I don't currently have a running kube cluster to test this against but you should basically be able to run all this in a single task with a loop using the kubernetes.core.k8s module

Here is what I believe should meet your requirement (provided your access to your kube instance is configured and ok in your environment and that you installed the above collection as described in the documentation)

- name: install my kube objects
  hosts: localhost
  gather_facts: false

  vars:
    obj_def_path: /path/to/your/obj_def_dir/
    obj_def_list:
      - food-pv.yaml
      - bar-pv.yaml
      - foo.yaml
      - bar.yaml
      - this-service.yaml
      - that-nodeport.yaml
      - something.yaml


  tasks:
    - name: Install all objects from def files
      k8s:
        src: "{{ obj_def_path }}/{{ item }}"
        state: present
        apply: true
      loop: "{{ obj_def_list }}"

  •  Tags:  
  • Related