The best way to interact with your Pods is to use the Kubernetes dynamic inventory plugin, which dynamically queries Kubernetes APIs using kubectl
command line available on controller node and tells Ansible what Pods can be managed.
To use the Kubernetes dynamic inventory plugins, you must install Kubernetes Python client, kubectl and OpenShift Python client on your control node (the host running Ansible).
$ pip install kubernetes openshift
Please refer to Kubernetes official documentation for installing kubectl on the given operating systems.
To use this Kubernetes dynamic inventory plugin, you need to enable it first by specifying the following in the ansible.cfg
file:
[inventory] enable_plugins = kubernetes.core.k8s
Then, create a file that ends in .k8s.yml
or .k8s.yaml
in your working directory.
The kubernetes.core.k8s
inventory plugin takes in the same authentication information as any other Kubernetes modules.
Here’s an example of a valid inventory file:
plugin: kubernetes.core.k8s
Executing ansible-inventory --list -i <filename>.k8s.yml
will create a list of Pods that are ready to be configured using Ansible.
You can also provide the namespace to gather information about specific pods from the given namespace. For example, to gather information about Pods under the test
namespace you will specify the namespaces
parameter:
plugin: kubernetes.core.k8s connections: - namespaces: - test
Since the inventory configuration file contains Kubernetes related sensitive information in plain text, a security risk, you may want to encrypt your entire inventory configuration file.
You can encrypt a valid inventory configuration file as follows:
$ ansible-vault encrypt <filename>.k8s.yml New Vault password: Confirm New Vault password: Encryption successful $ echo "MySuperSecretPassw0rd!" > /path/to/vault_password_file
And you can use this vaulted inventory configuration file using:
$ ansible-inventory -i <filename>.k8s.yml --list --vault-password-file=/path/to/vault_password_file
See also
The GitHub Page of Kubernetes Python client
The issue tracker for Kubernetes Python client
The GitHub Page of OpenShift Dynamic API client
The issue tracker for OpenShift Dynamic API client
Installation guide for installing Kubectl
An introduction to playbooks
Using Vault in playbooks
© 2012–2018 Michael DeHaan
© 2018–2021 Red Hat, Inc.
Licensed under the GNU General Public License version 3.
https://docs.ansible.com/ansible/latest/scenario_guides/kubernetes_scenarios/k8s_inventory.html