What does 'with context' mean when doing an import? - salt-stack

I've been looking for an explanation in the SaltStack docs about what 'with context' means. But there's only examples of using context.
What is 'context'?
What does it do here? And why is Debian ignored in the map.jinja file? (for example map.log_dir seems to "jump down" a level)
# config.sls
{% from "bind/map.jinja" import map with context %}
include:
- bind
{{ map.log_dir }}:
file.directory:
- user: root
- group: {{ salt['pillar.get']('bind:config:group', map.group) }}
- mode: 775
- require:
- pkg: bind
# map.jinja
{% set map = salt['grains.filter_by']({
'Debian': {
'pkgs': ['bind9', 'bind9utils', 'dnssec-tools'],
'service': 'bind9',
'config_source_dir': 'bind/files/debian',
'zones_source_dir': 'zones',
'config': '/etc/bind/named.conf',
'local_config': '/etc/bind/named.conf.local',
'key_config': '/etc/bind/named.conf.key',
'options_config': '/etc/bind/named.conf.options',
'default_config': '/etc/default/bind9',
'default_zones_config': '/etc/bind/named.conf.default-zones',
'named_directory': '/var/cache/bind/zones',
'log_dir': '/var/log/bind9',
'user': 'root',
'group': 'bind',
'mode': '644'
},
'RedHat': {
'pkgs': ['bind'],
'service': 'named',
'config_source_dir': 'bind/files/redhat',
'zones_source_dir': 'zones',
'config': '/etc/named.conf',
'local_config': '/etc/named.conf.local',
'default_config': '/etc/sysconfig/named',
'named_directory': '/var/named/data',
'log_dir': '/var/log/named',
'user': 'root',
'group': 'named',
'mode': '640'
},

Since this page is the top search result for "jinja import with context" (and the other answer doesn't actually say what it does), and I keep coming back to this page every couple of months when I need to mess with Salt but forget what with context does:
When you import foo in jinja, normally the macros you've defined in foo don't have access to variables in the file you're importing it from. As an optimization, Jinja will then cache this if you import again later in the file. If instead you do import foo with context, then the macros in foo can access the variables in the file it's being imported from. The trade-off is that Jinja no longer caches foo, so you pay in render time.
When you do include, your variables do get passed into the other file. You then render the contents of the other file and paste them in. If you do include foo without context, you don't pass the variables of the current file in. This is useful, because Jinja will optimize this by caching the contents of foo, speeding up your render.

with context is part of the jinja template engine.
You can read more about it in the jinja docs:
import context
behavior
context API
Regarding the missing debian data - is this your complete map.jinja? the snippet misses }, default='Debian') %} according to grains.filter_by

Related

sending customized salt event with cmd.run and onfail

I want to trigger custom named event if sls state fails.
I have following code:
check-if-needs-restarting:
{% if grains['os'] == 'CentOS' %}
cmd.run:
- name: needs-restarting -r
- onfail:
- cmd.run:
- name: salt-call event.send needs-restarting
{% endif %}
but somehow it crashes salt renderer:
An un-handled exception was caught by salt's global exception handler:
SaltRenderError: Could not locate requisite of [cmd] present in state with name
Any idea why? I tried fire_event instead but thn I dont have custom name I want "needs-restarting"
onfail like other global state arguments works only with states as arguments
See examples in the official documentation

Symfony Encore multiple asset manifests

I have a question regarding Encore in Symfony 3.4 and asset versioning.
In my webpack.config.jsI have two configurations.
First is for JS files, the other one for compiling .less.
Each configuration is reset by Encore.reset()
Output bundles are generating manifest with versioning via .enableVersioning, so I have two manifest.json in
web/js/manifest.json
web/stylesheets/manifest.json
According to docs, to have my assets loaded via manifest I need to declare it in config.yml
assets:
base_path: "%myapp.http.site_assets_suffix%"
stylesheets:
json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
If I want to link to style.css generated by webpack, I use
asset("stylesheets/style.css")
But in my application I have two manifests and I think this can't be changed due to two Encore configurations.
I've tried adding something in likes of
packages:
stylesheets:
json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
js:
json_manifest_path: "%kernel.project_dir%/web/assets/js/manifest.json"
because I saw that somewhere, but unfortunately this won't work at all.
I've thought about combining two manifests into one in last webpack entry point, but this can be time consuming.
Is there any other solution than combining manfiests or combining js + less compilation into one big Encore task?
I've found a solution
assets:
base_path: 'path%'
packages:
noversion:
version: false
version_format: "%%1$s"
base_path: "path%"
stylesheets:
json_manifest_path: "%kernel.project_dir%/web/assets/stylesheets/manifest.json"
js:
json_manifest_path: "%kernel.project_dir%/web/assets/js/manifest.json"
admin:
json_manifest_path: "%kernel.project_dir%/web/assets/js/admin/manifest.json"
And then in .twig files, you need to call it as
<script src="{{ asset('assets/DIRNAME/WEBPACK_ENTRY_NAME_HERE', ASSET_PACKAGE_NAME_HERE) }}"></script>
In my case
<script src="{{ asset('assets/js/backend.js', 'js') }}"></script>
Where WEBPACK_ENTRY_NAME is the name of the Webpack/Encore bundle from webpack.config.js, in my case
.setOutputPath('./web/assets/js')
.setPublicPath('/assets/js')
.addEntry('backend',
Sorry for delayed answer, but I forgot about it.
Webpack Encore use webpack-manifest-plugin to generate manifest.json file.
According to the doc, you can specify an options.seed when you setup your config.
A cache of key/value pairs to used to seed the manifest. This may include a set of custom key/value pairs to include in your manifest, or may be used to combine manifests across compilations in multi-compiler mode. To combine manifests, pass a shared seed object to each compiler's ManifestPlugin instance.
Encore.configureManifestPlugin(options => {
let seed;
try {
// require your existing manifest content if exists
seed = require(path.join(outputPath, 'manifest.json'));
}
catch (e) {
// fallback if manifest.json is missing
seed = {};
}
// inject your latest config as seed.
// The plugin will update it and rewrite manifest.json with correct values (overwrite existing keys, append news)
options.seed = seed;
// Also i add a trick to avoid "License.txt" entries
options.generate = function(seed, files, entrypoints) {
// trick to avoid generate useless versionned entries like License
const filesWithoutLicense = files.filter(file => {
return file.path.match(/.*LICENSE.*/) === null;
});
const newManifestContent = filesWithoutLicense.reduce(
(newManifestContent, file) => {
newManifestContent[file.name] = file.path;
return newManifestContent;
},
seed
);
return newManifestContent;
}

Get base_path in twig file -- Drupal 8

How can i get the base path of drupal installation in twig file?
For example i need to get http://localhost/drupal/.
I have tried
{{ base_path }}
But it's returning empty.
{{ directory }}
This is returning the theme path. but i need the base path to complete the url. Is there any way to do this?
#Ditto P S To get base path on twig you declare a variable in .theme file inside a preprocess
andthen simply use 'base_path_success' variable in twig as
{{ base_path_success }}
You can declare variable inside any of the preprocess like
function ttnd_preprocess_node(&$variables) {}
OR
function ttnd_preprocess_block(&$variables) {}
Here ttnd is themename.
For more information you can use the below link
https://drupal.stackexchange.com/questions/205289/base-path-drupal-8
You can get the hostname, "localhost/drupal/", directly from the getHost() request:
$host = \Drupal::request()->getHost();
In some cases you might want to get the schema as well, fx http://localhost/drupal/:
$host = \Drupal::request()->getSchemeAndHttpHost();
Source : https://drupal.stackexchange.com/a/202811/

An exception has been thrown during the rendering of a template ("The "yml~" translation loader is not registered.")

I have this problem, when I try to load page after installed LexikTranslationBundle
An exception has been thrown during the rendering of a template ("The
"yml~" translation loader is not registered.") in
backendLayoutBundle:Layout:empty.html.twig at line 8.
empty.html.twig at line 8:
{% trans %}Reporting application{% endtrans %}
config:
lexik_translation:
fallback_locale: en # (required) default locale to use
managed_locales: [en] # (required) locales that the bundle have to manage
base_layout: "LexikTranslationBundle::layout.html.twig" # layout used with the translation edition template
use_yml_tree: false # if "true" we will print a nice tree in the yml source files. It is a little slower.
grid_input_type: text # define field type used in the grid (text|textarea)
storage:
type: orm # where to store translations: "orm", "mongodb" or "propel"
object_manager: default # The name of the entity / document manager which uses different connection (see: http://symfony.com/doc/current/cookbook/doctrine/multiple_entity_managers.html)
# When using propel, this can be used to specify the propel connection name
resources_registration:
type: all # resources type to register: "all", "files" or "database"
managed_locales_only: true # will only load resources for managed locales

How do I make one custom state dependent on another?

How do I make one custom state dependent on another with a requisite in an sls file?
Example: Two custom states in a _states/seuss.py module:
# seuss.py
def green_eggs():
return {'name': 'green_eggs', 'result': True, 'comment': '', 'changes': {}}
def ham():
return {'name': 'ham', 'result': True, 'comment': '', 'changes': {}}
I want ham to be dependent on green_eggs:
# init.sls
have_green_eggs:
seuss.green_eggs:
- require:
- user: seuss
have_ham:
seuss.ham:
- require:
- ???
How do I make ??? a dependency on the successful completion of green_eggs?
You would want:
have_ham:
seuss.ham:
- require:
- seuss: have_green_eggs
However, you are currently defining two states of a seuss resource, which means that either a seuss.ham or a seuss.green_eggs called have_green_eggs could fulfil that requirement.
If you don't want that, then you will have to define the states in separate files (e.g. seuss_ham.exists and seuss_green_eggs.exists).

Resources