I have a file with variables that I use in my playbook:
net_interfaces:
...
- name: "eth0"
ip: "192.168.1.100"
mask: "255.255.255.0"
gateway: "192.168.1.1"
...
and I want to deploy some configs with this variables, for example ifcfg-eth0:
DEVICE={{ item.name }}
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=static
IPADDR={{ item.ip }}
NETMASK={{ item.netmask }}
GATEWAY={{ item.gateway }}
but sometimes there is no gateway variable for item and in this case I want to remove string
GATEWAY={{ item.gateway }}
from this config file on the target machine. How can I achieve this without creating another task for a certain hosts?
Add condition:
{% if item.gateway is defined %}
GATEWAY={{ item.gateway }}
{% endif %}
Another (and better) way is to use 'default' filter because in this case we can check if some variable was defined and set it's default value if it wasn't. Example:
{{ my_string_value | default("awesome") }}
Related
I'm trying to create a sudo file for each user.
Playbook:
- name:
hosts: all
gather_facts: false
tasks:
- name:
template:
src: sudo.j2
dest: "/etc/sudoers.d/{{item.name}}"
loop: "{{userinfo}}"
when: "'admins' in item.groupname"
Var file:
userinfo:
- groupname: admins
name: bill
- groupname: admins
name: bob
- groupname: devs
name: bea
Jinja file:
{% for item in userinfo %}
{% if item.groupname=="admins" %}
{{item.name}} ALL=ALL NOPASSWD:ALL
{% endif %}
{% endfor %}
What I am getting is two files but with information of both users.
bill ALL=ALL NOPASSWD:ALL
bob ALL=ALL NOPASSWD:ALL
How do I make it work such that each file contains information of that user only
The issue is that you have 2 loops: one in the playbook, the other in the template jinja file; try leaving the template file with the templated information only
{{ item.name }} ALL=ALL NOPASSWD:ALL
I am using an if condition utilizing grain item within a state which triggered by reactor.
and I got an error message Jinja variable 'dict object' has no attribute 'environment'
=================================================
REACTOR config:
cat /etc/salt/master.d/reactor.conf
reactor:
- 'my/custom/event':
- salt://reactor/test.sls
==============================
test.sls
cat /srv/salt/reactor/test.sls
sync_grains:
local.saltutil.sync_grains:
- tgt: {{ data['id'] }}
{% if grains['environment'] in ["prod", "dev", "migr"] %}
test_if_this_works:
local.state.apply:
- tgt: {{ data['id'] }}
- arg:
- dummy_state
{% endif %}
===================================
dummy_state/init.sls
cat /srv/salt/dummy_state/init.sls
create_a_directory:
file.directory:
- name: /tmp/my_test_dir
- user: root
- group: root
- makedirs: True
=================================================
salt 'salt-redhat-23.test.local' grains.item environment
salt-redhat-23.test.local:
----------
environment:
prod
=================================================
salt-redhat-23 ~]# cat /etc/salt/grains
role: MyServer
environment: prod
================================================
If I change the test.sls and use instead of custom grain a grain which salt-master is taking by default then it will works. Also it will work without the if condition in the state.
Do you know why this is happening?
Thank you all in advance.
Issue resolved.
You cannot use custom grains with Reactor directly, you need to call another state to be able to add condition there.
for instance:
cat /etc/salt/master.d/reactor.conf
reactor:
- 'my/custom/event':
- salt://reactor/test.sls
test.sls
# run a state using reactor
test_if_this_works:
local.state.apply:
- tgt: {{ data['id'] }}
- arg:
- reactor.execute
execute.sls
{% set tst = grains['environment'] %}
{% if tst in ['prod', 'dev', 'test', 'migr'] %}
create_a_directory:
file.directory:
- name: /tmp/my_test_dir
- user: root
- group: root
- makedirs: True
{% endif %}
this will work with the if condition, if you try to add the if statement on the test.sls it will not work.
How to print new line character when sending emails? I'm sending it to gmail. The character \n prints literally. I even tried </br> tag and yaml mutliline and none of them work.
- alert: KubernetesPodImagePullBackOff
expr: kube_pod_container_status_waiting_reason{reason=~"ContainerCreating|CrashLoopBackOff|ErrImagePull|ImagePullBackOff"} > 0
for: 1s
labels:
severity: warning
annotations:
summary: "Kubernetes pod crash looping (instance {{ $labels.instance }}"
description: "Pod {{ $labels.pod }} is crash looping\n VALUE = {{ $value }}\n LABELS: {{ $labels }}"
You need to rewrite default template in Alertmanager for E-mails.
You need to replace something like
{{ .Annotations.description }}
in template by
{{ .Annotations.description | safeHtml }}
I wrote for my own email template, if you have not your own, you may create it from
https://github.com/prometheus/alertmanager/blob/master/template/default.tmpl
and edit
{{ range .Annotations.SortedPairs }} - {{ .Name }} = {{ .Value }}
in the same manner with
{{ .Value | safeHtml }}
Also read this answer
prometheus using html content in alerts annotations and using it in email template
I'm very new to saltstack and still learning so if there is a better way of doing things please let me know.
I'm trying to pass in override values and cascade use that override value in variable pillar files. So I plan to have a default.sls file that contains variables that all the other pillars will use. I want to also be able to override the default.sls variables from the command line.
Here is what I'm doing:
File structure:
/pillar/top.sls
/pillar/default.sls
/pillar/test.sls
In /pillar/top.sls
base:
'*':
- default
'test':
- match: glob
- test
In /pillar/default.sls
{% set home_location = salt['cmd.shell']('eval echo "~ec2-user"') %}
environment: dev
uniqueid: all
side: a
region: myregion
app: myapp
ipaddress: {{ grains['ip4_interfaces']['eth0'][0] }}
hostname: {{ grains['host'] }}
homedir: {{ home_location }}
docker:
- pip:
- version: 4.0.2
In /pillar/test.sls
test:
- log:
- group: logs-{{ pillar['environment'] }}-{{ pillar['uniqueid'] }}-{{ pillar['app'] }}
- stream: logs_{{ pillar['side'] }}_mysupertest_{{ pillar['ipaddress'] }}
Here is the command I am running locally (masterless):
salt-call --id 'test' pillar.items --local pillar='{"environment":"uat","side":"b"}'
It throws the following error:
SaltRenderError: Jinja variable 'salt.utils.context.NamespacedDictWrapper object' has no attribute 'environment'
[CRITICAL] Pillar render error: Rendering SLS 'test' failed. Please see master log for details.
So it's not getting the values from the default.sls file. What am I doing wrong?
Also I have tried adding the following to the test.sls file with the same results:
include:
- pillar://default
I'm trying to inline this so the rendered page isn't 100,000 lines long.
It seems the spaceless tag does nothing here.
Input:
{% for log in logs -%}
{% spaceless %}
{
id: {{ log.id }},
description: '{{ log.description }}'
},
{% endspaceless %}
{% endfor -%}
Expected Output:
{id:17186,description:'Test Log'},
{id:17187,description:'Test Log 2'},
Output:
{
id: 17186,
description: 'Test Log'
},
{
id: 17187,
description: 'Test Log 2'
},
Like the documentation says, you can "use the spaceless tag to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text."
You can instead control whitespace e.g. like this:
{% for log in logs -%}
{
{{- 'id' }}: {{ log.id }},
{{- 'description' }}: '{{ log.description }}'
{{- '},' }}
{%- endfor %}
The above produces this:
{id: 17186,description: 'Test Log'},{id: 17187,description: 'Test Log 2'},
The downside is that the Twig code is much uglier.
Here's an alternative using string interpolation:
{% for log in logs -%}
{
{{- 'id' }}: {{ log.id }},
{{- 'description' }}: {{ "'#{log.description}'" -}}
},
{%- endfor %}
{id: 17186,description: 'Test Log'},{id: 17187,description: 'Test Log 2'},
The Twig code looks now better, but notice that single quotes got converted to '. You may or may not want to do something about that.
You could also do like the documentation suggests and use a third-party library like Tidy.