Reputation: 31
Below are my jinja2 template file and the variables used to populate it. However I want to include a new section only if aditional_keys = true
. Is this possible?
My variable
- { name: 'container1', version: '1.0.0.0', port: '', registry_path: 'container1', replicas: '1', namespace: 'general', aditional_keys: 'false'}
- { name: 'container2', version: '3.6.14.1', port: '8080', registry_path: 'container2', replicas: '1', namespace: 'general', aditional_keys: 'true'}
My template
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: {{ item.name }}
environment: {{ location }}_{{ env }}
name: {{ item.name }}
namespace: "{{ item.namespace }}"
spec:
replicas: {{ item.replicas }}
selector:
matchLabels:
app: {{ item.name }}
environment: {{ location }}_{{ env }}
template:
metadata:
labels:
app: {{ item.name }}
environment: {{ location }}_{{ env }}
spec:
containers:
- envFrom:
- configMapRef:
name: {{ item.name }}
image: registry.com/{{ item.registry_path }}:{{ item.version }}
imagePullPolicy: Always
name: {{ item.name }}
ports:
- containerPort: {{ item.port }}
protocol: TCP
I tried adding this but I am obviously not calling the variable correctly
{% if item.additional_keys == true %}
env:
- name: PRIVATE_KEY
valueFrom:
secretKeyRef:
key: id_{{ item.name }}_rsa
name: id-{{ item.name }}-rsa-priv
optional: false
- name: PUBLIC_KEY
valueFrom:
secretKeyRef:
key: id_{{ item.name }}.pub
name: id-{{ item.name }}-rsa-pub
optional: false
{% else %}
{% endif %}
Upvotes: 0
Views: 166
Reputation: 44799
To start with, literal compare to boolean values is one of the ansible-lint rules you might want to follow.
Now there are 2 real issues in your above example.
aditional_keys
) while you spelled it correctly in your template (ad
ditional_keys
)'false'
) while you expect a boolean (false
). Meanwhile, it often happens in ansible that correct boolean values can be turned into strings upon parsing (e.g. extra_vars on the command line). To overcome this, the good practice is to systematically transform the value to a boolean with the bool
filter when you don't totally trust the source.Once your fix the variable name and boolean definition in your var file as additional_keys: false
, the following conditional in your template will make sure you don't get into that trouble again:
{% if item.additional_keys | bool %}
Upvotes: 1