How to pass variables to a Kubernetes YAML file from Ansible?

6/11/2018

I am to trying to pass variables to kubernetes YAML file from Ansible but somehow values are not being populated.

Here is my playbook:

- hosts: master
  gather_facts: no
  vars:
    logstash_port: 5044
  tasks:
   - name: Creating kubernetes pod
     command: kubectl create -f logstash.yml

logstash.yml:

apiVersion: v1
kind: Pod
metadata: logstash
spec:
  containers:
  - name: logstash
    image: logstash
    ports:
      - containerPort: {{ logstash_port }}

Is there a better way to pass arguments to Kubernetes YAML file that is being invoked using command task?

-- Srinivas
ansible
kubernetes

1 Answer

6/11/2018

What you are trying to do has no chance of working. Kubernetes (the kubectl command) has nothing to do with Jinja2 syntax, which you try to use in the logstash.yml, and it has no access to Ansible objects (for multiple reasons).


Instead, use k8s_raw module to manage Kubernetes objects.

You can include Kubernetes' manifest directly in the definition declaration and there you can use Jinja2 templates:

- k8s_raw:
    state: present
    definition:
      apiVersion: v1
      kind: Pod
      metadata: logstash
      spec:
        containers:
          - name: logstash
            image: logstash
            ports:
              - containerPort: "{{ logstash_port }}"

Or you can leave your logstash.yml as is, and feed it using the template lookup plugin:

- k8s_raw:
    state: present
    definition: "{{ lookup('template', 'path/to/logstash.yml') | from_yaml }}"

Notice if you used Jinja2 template directly in Ansible code, you must quote it. It's not necessary with the template plugin.

-- techraf
Source: StackOverflow