I'm working on pretty basic steps my Salt recipes are supposed to to depending on the kind and Version of an installed CMS or Shop-System.
Basically a Python library I wrote scans a directory and determines the CMS (WordPress, Joomla, Typo3, Magento, ...) and the installed Version and then does the same Tasks with tweaked approaches depending on what System in which Version is present.
The trick is, that it is not possible to know beforehand which system is in place, and for example the Database Credentials need to be updated. That's why an appscanner is being executed with returns a JSON or all the apps and their information found in a directory recursively. For the scan here it is configured to only return the application where installation directory is equal to the directory it is targeting - thus is only returns a single application.
The problem is, it isn't always possible to determine the software or its version so the following Jinja Template can throw the "has no element 0" error.
{% set APP_SCAN_RESULT = salt['cmd.shell']('python /modules/appscanner.py ' + pillar.volumeMounts.web + pillar.installPath ) | load_json %}
{% if APP_SCAN_RESULT[0]['AppVersion'] is defined %}
{% set CURRENT_SOFTWARE = APP_SCAN_RESULT[0]['AppName'] %}
{% set CURRENT_VERSION = APP_SCAN_RESULT[0]['AppVersion'] %}
{% set CURRENT_INSTALLMODE = APP_SCAN_RESULT[0]['InstallationMode'] %}
{% else %}
{# Do nothing #}
{% endif %}
Instead of throwing the error though I want it to just skip the whole process and finish gracefully without having done anything. If the application and its version where determined it just continues with something like
{% if CURRENT_SOFTWARE == "X" and CURRENT_VERSION.split('.')[0] == '1' %}
{# Do A on X #}
{% elif CURRENT_SOFTWARE == "X" and CURRENT_VERSION.split('.')[0] == '2' %}
{# Do B on X #}
{% elif CURRENT_SOFTWARE == "Y" %}
{# Do C on Y #}
{% elif ... %}
Also: yes I trigger the python module via cmd.shell since I haven't figured out the whole "python in jinja in salt" thing yet. Any hints on that front are welcome too.
The big question though is, how do I get the code to continue even if APP_SCAN_RESULT[0] is empty?
Check whether the list is empty before trying to use it:
{% if APP_SCAN_RESULT|length > 0 %}
{# do stuff #}
{% endif %}
I haven't figured out the whole "python in jinja in salt" thing yet.
Put it in salt://_modules/
and call it as salt["appscanner.get"](...)
.
You can also change the structure of what it returns to make using it simpler.