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

<p>Here is my playbook:</p>

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

<p><code>logstash.yml</code>:</p>

<pre><code>apiVersion: v1
kind: Pod
metadata: logstash
spec:
  containers:
  - name: logstash
    image: logstash
    ports:
      - containerPort: {{ logstash_port }}
</code></pre>

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

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

<hr>

<p>Instead, use <a href="https://docs.ansible.com/ansible/latest/modules/k8s_raw_module.html" rel="nofollow noreferrer"><code>k8s_raw</code> module</a> to manage Kubernetes objects.</p>

<p>You can include Kubernetes' manifest directly in the <code>definition</code> declaration and there you can use Jinja2 templates:</p>

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

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

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

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