Bash operation of counting array elements in inaccessible

I wonder how this can work in an unasked task?

 - shell: |
     y=(aa bb); echo "${#y[@]}"
   register: r

It currently provides the following error

ERROR: An error occurred while analyzing the task "shell y = (aa bb); echo" $ {# y [@]} "\ n '. Make sure that the quotation marks are appropriate or escaped properly

.. because of the '#' character. I cannot avoid this, because otherwise the invalid bash operation works. If I run away, I get:

$ ansible -c localhost -m shell -a 'y=(aa bb); echo "${\#y[@]}"' -i hosts.ini test-host

 localhost | FAILED | rc=1 >>
 /bin/sh: ${\#y[@]}: bad substitution

The current equivalent result of this op in linux cmdline:

$ y=(aa bb); echo "${#y[@]}"
2

this seems to be a problem as I have tried all the quoting combinations. I discovered a problem here just in case: https://github.com/ansible/ansible/issues/16968

, bash, :

$ a="aaa"; echo "${#a}"
3
$ ansible -c localhost -m shell -a 'a="aaa"; echo "${#a}"' -i hosts.ini test-host

! , jinja2, : a = "aaa"; echo "$ {# a}"

UPDATE:

github, ​​, , , - ansible==1.9.6.

@konstantin-suvorov 2.1+ jinja templating comment system. , , , :

y=(aa bb cc); g=("${!y[@]}"); res=`expr ${g[-1]} + 1`; echo $res

, , ! , #. -, !

+4
2

{# - jinja, .

{ #:

- shell: |
         y=(aa bb cc); echo "${{"{"}}#y[@]}"

: :

$ansible --version
ansible 2.1.1.0
$cat xx.yml
---
- hosts: localhost
  connection: local
  tasks:
    - shell: |
             y=(aa bb cc); echo "${{"{"}}#y[@]}"
      register: result
    - debug: var=result.stdout
$ansible-playbook xx.yml
PLAY [localhost] ***************************************************************
TASK [command] *****************************************************************
changed: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => {
    "result.stdout": "3"
}
0

:

{# - jinja, .

. , :

 - shell: |
     y=(aa bb); y_length=#y[@]; echo "${y_length[@]}"
   register: r

, {#.

0

Source: https://habr.com/ru/post/1650256/


All Articles