Template in command line sensor command

Hi All,
I need help on how to configure a command line sensor command template. What i would like to achive is to create command line sensor like this one:

- platform: command_line
  name: Server Disk1 Temperature
  command:  ssh -F /config/ssh_config -i /config/ssh/id_rsa [email protected] 'smartctl -a /dev/sdb | grep Temperature_Celsius | awk "{print \$10}"'
  unit_of_measurement: "°C"

But it should only run when other binary sensor is on- so i thought this would work:

- platform: command_line
  name: Server Disk1 Temperature
#  command:  ssh -F /config/ssh_config -i /config/ssh/id_rsa [email protected] 'smartctl -a /dev/sdb | grep Temperature_Celsius | awk "{print \$10}"'
  command: > 
    {% if is_state('binary_sensor.server_online','on') -%} 
    ssh -F /config/ssh_config -i /config/ssh/id_rsa [email protected] 'smartctl -a /dev/sdb | grep Temperature_Celsius | awk "{print \$10}"' 
    {%- endif %}
  unit_of_measurement: "°C"

But it does not…
What do i do wrong?

A similar question.
I got a template sensor host_type which could be equal to "RPi".
Also, there is a command_line sensor:

# RPi CPU throttling
  - platform: command_line
    name: "RPi CPU get_throttled"
    command: >-
      {% set CMD = "cat /sys/devices/platform/soc/soc:firmware/get_throttled" -%}
      {%- set HOST_TYPE = states('sensor.host_type') -%}
      {%- if HOST_TYPE is match('RPi',ignorecase=False) -%}
      {{ CMD }}
      {%- else -%}
      {{ "echo" }}
      {%- endif %}
    value_template: "{{ value }}"
    scan_interval: 60

which seems not working and I got errors in Log:

2021-10-27 22:33:49 ERROR (SyncWorker_12) [homeassistant.components.command_line] Command failed: {% set CMD = "cat /sys/devices/platform/soc/soc:firmware/get_throttled" -%}echo

What is wrong in my setup?
Do command_line sensors support templates?

I suspect that if .. else ... endif constructions are NOT supported


Surely I may use a separate sensor for the command itself:

  - platform: template
    sensors:
      rpi_cpu_get_throttled_command:
        value_template: >-
          {% set CMD = "cat /sys/devices/platform/soc/soc:firmware/get_throttled" -%}
          {%- set HOST_TYPE = states('sensor.host_type') -%}
          {%- if HOST_TYPE is match('RPi',ignorecase=False) -%}
          {{ CMD }}
          {%- else -%}
          {{ "echo" }}
          {%- endif %}

  - platform: command_line
    name: "RPi CPU get_throttled"
    command: "{{ states('sensor.rpi_cpu_get_throttled_command') }}"
    value_template: "{{ value }}"
    scan_interval: 60

But it is an additional code…
Moreover - it just DOES NOT work too:

2021-10-28 00:53:06 ERROR (SyncWorker_12) [homeassistant.components.command_line] Command failed: {{ states('sensor.rpi_cpu_get_throttled_command') }}

Even this template does not work:

    command: "{{ 'ls' }}"

with error:

2021-10-28 01:33:23 ERROR (SyncWorker_3) [homeassistant.components.command_line] Command failed: {{ 'ls' }}

OK, this works w/o template:

    command: "ls"

So, what is going on? Template support is broken?

Registered an issue:

Templates in command_line sensors still do not work as they do in a conventional template sensors.
The old problem is still there:

Yeah I ran into the issue of this integration not supporting multi-line templates just last week.

This example does not have multi-line templates - but it does not work:

    command: >-
      {% set KEYS = "a" -%}
      ls -{{KEYS}}
2022-07-22 04:10:23 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'KEYS' is undefined when rendering 'set KEYS = "a" -%} ls -{{KEYS}}'
2022-07-22 04:10:23 ERROR (SyncWorker_23) [homeassistant.components.command_line] Command failed: {% set KEYS = "a" -%} ls -

But this version should work:

    command: >-
      ls -{% set KEYS = "a" -%}{{KEYS}}

but in this particular case it will give an error “state > 255 chars”, but this is another story.
May be tested with this example:

    command: >-
      ls {% set KEYS = "automations.yaml -la" -%}{{KEYS}}

Yes it does:

Yes, you are right, it is considered as a multiline probably)))
So, the possible problem is multiline templates.
It explains why my problem cases described in the issue do not work.

Interestingly, why this case does not work?

command: "{{ 'free -h' }}"

This is a one-line template)))

P.S. Probably you should put a comment in the issue regarding your brilliant guess about “multiline templates”, it really seems to be a reason.

Does this work?

command: 'free -h'

Surely it works…
That stupid example was made just for testing.

Ok, weird. I was working under the assumption that the > in command: > was being interpreted as part of the command, but it must be more than that.

Here is what I currently have to do:

command: " {% ... -%} {%- ... -%}  {%- ... -%}  {%- ... -%} {{ ... }}"

instead of

command: >-
  {% ... -%}
  {%- ... -%}
  {%- ... -%}
  {%- ... -%}
  {{ ... }}

Update:
No, this does not work too.

command: "{% set SENSOR_SETTINGS = 'sensor.xxx' -%}{{state_attr(SENSOR_SETTINGS,'command_ip_address')}}"

Although this is a one-line template.

2022-07-22 04:53:07 ERROR (SyncWorker_32) [homeassistant.components.command_line.sensor] Error rendering command template: UndefinedError: 'SENSOR_SETTINGS' is undefined
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 421, in async_render
render_result = _render_with_context(self.template, compiled, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1906, in _render_with_context
return template.render(**kwargs)
File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 1301, in render
self.environment.handle_exception()
File "/usr/local/lib/python3.10/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "<template>", line 1, in top-level template code
File "/usr/local/lib/python3.10/site-packages/jinja2/sandbox.py", line 393, in call
return __context.call(__obj, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2054, in wrapper
return func(hass, *args[1:], **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1371, in state_attr
if (state_obj := _get_state(hass, entity_id)) is not None:
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 921, in _get_state
return _get_template_state_from_state(hass, entity_id, hass.states.get(entity_id))
File "/usr/src/homeassistant/homeassistant/core.py", line 1308, in get
return self._states.get(entity_id.lower())
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1932, in _fail_with_undefined_error
raise ex
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1923, in _fail_with_undefined_error
return super()._fail_with_undefined_error(*args, **kwargs)
jinja2.exceptions.UndefinedError: 'SENSOR_SETTINGS' is undefined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/command_line/sensor.py", line 161, in update
rendered_args = args_compiled.render(args_to_render)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 393, in render
).result()
File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 446, in result
return self.__get_result()
File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 391, in __get_result
raise self._exception
File "/usr/src/homeassistant/homeassistant/util/async_.py", line 64, in run_callback
future.set_result(callback(*args))
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 423, in async_render
raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: UndefinedError: 'SENSOR_SETTINGS' is undefined

Bypassing:

    command: >-
      echo ;
      {% set SENSOR_SETTINGS = 'sensor.xxx' -%}{{ state_attr(SENSOR_SETTINGS,'command_ip_address') }}