- In this post I will walk you through on how to deploy/un-deploy Kubernetes objects using Ansible playbook
Pre-requisites
- Setup Ansible control machine (from where scripts will be run)
- Define user and SSH key
- Allow user for for sudo without password
What we will do
- Create inventory file called "inventory.ini" in home directory or any other folder. Default location of inventory file in ''etc/ansible/hosts' when custom inventory file is not specified
- Create "ansible.cfg" file and specify inventory file created in step above.
- Create ansible playbook
- Deploy namespace on Kubernetes using playbook
Create Inventory file
Create a file "inventory.ini" specifying the hosts info.
[master]K8s-master kubernetes_role=master
[workers]
K8s-worker1 kubernetes_role=nodeK8s-worker2 kubernetes_role=node
Create "ansible.cfg file"
In the same folder where "inventory.ini" is created, create a file
"ansible.cfg" and specify the below...
[defaults]remote_user = <specify_user_with_SSH_setup>host_key_checking = falseask_pass = noinventory = inventory.iniinterpreter_python = auto_legacy_silent
[privilege_escalation]become = yesbecome_ask_pass = nobecome_method = sudobecome_user = root
Test the setup by trying to ping the hosts :
ansible all -m ping
The k8s module requires the OpenShift Python client to communicate with the
Kubernetes API. So before using the k8s role, you need to install the client.
Since it’s installed with pip, we need to install Pip as well.
Create file ‘InstallAnsibleK8sModule.yaml’ with the below content
- hosts: K8s-master
pre_tasks:- name: Ensure Pip is installed.package:name: python3-pipstate: present
- name: Ensure OpenShift client is installed.pip:name: openshiftstate: present
To run playbook
ansible-playbook InstallAnsibleK8Module.yaml
Deploying kubernetes objects can be achieved in 2 ways...
- Create a playbook 'CreateNameSpace.yaml'
Specify the task to run from yaml file.- hosts: k8s-master
pre_tasks:- name: Ensure Pip is installed.package:name: python3-pipstate: present
- name: Ensure OpenShift client is installed.pip:name: openshiftstate: presenttasks:- name: Creating Demo namespace by applying YAML definition file.k8s:state: presentdefinition: "{{ lookup('file', 'demo-namespace.yaml') | from_yaml }}"
- Specify the task to run from inline specification.
- hosts: k8s-masterpre_tasks:- name: Ensure Pip is installed.package:name: python3-pipstate: present
- name: Ensure OpenShift client is installed.pip:name: openshiftstate: presenttasks:- name: Creating DEMO namespace by applying inline definition.k8s:state: presentdefinition:apiVersion: v1kind: Namespacemetadata:name: demo-systemlabels:app: demo
To run playbook
ansible-playbook CreateNamespace.yaml
Un-deploying kubernetes object...
To remove the namespace, you can create another playbook
‘RemoveNamespace.yaml’ (which can be in-line or yaml file based) and set the
state to absent
state: absent
To run playbook
ansible-playbook
RemoveNamespace.yaml