Error failed at splitting arguments either an unbalanced jinja2 block or quotes

Issue Type Bug report Ansible and Ansible Lint details ansible 2.7.6 ansible-lint 4.0.1 Desired Behaviour To pass? Actual Behaviour (Bug report only) Traceback (most recent call last): File "/...

Issue Type

  • Bug report

Ansible and Ansible Lint details

ansible 2.7.6
ansible-lint 4.0.1

Desired Behaviour

To pass?

Actual Behaviour (Bug report only)

Traceback (most recent call last):
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/bin/ansible-lint", line 11, in <module>
    sys.exit(main())
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansiblelint/__main__.py", line 187, in main
    matches.extend(runner.run())
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansiblelint/__init__.py", line 229, in run
    for child in ansiblelint.utils.find_children(arg, self.playbook_dir):
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansiblelint/utils.py", line 174, in find_children
    for token in split_args(child['path']):
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansible/parsing/splitter.py", line 264, in split_args
    raise AnsibleParserError(u"failed at splitting arguments, either an unbalanced jinja2 block or quotes: {0}".format(args))
ansible.errors.AnsibleParserError: failed at splitting arguments, either an unbalanced jinja2 block or quotes: /Users/ssbarnea/rdo/harem/contribs/kubespray/roles/download/tasks/download_{%
Traceback (most recent call last):
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/bin/ansible-lint", line 11, in <module>
    sys.exit(main())
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansiblelint/__main__.py", line 187, in main
    matches.extend(runner.run())
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansiblelint/__init__.py", line 229, in run
    for child in ansiblelint.utils.find_children(arg, self.playbook_dir):
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansiblelint/utils.py", line 174, in find_children
    for token in split_args(child['path']):
  File "/Users/ssbarnea/.cache/pre-commit/reporaW0Ij/py_env-python2.7/lib/python2.7/site-packages/ansible/parsing/splitter.py", line 264, in split_args
    raise AnsibleParserError(u"failed at splitting arguments, either an unbalanced jinja2 block or quotes: {0}".format(args))
ansible.errors.AnsibleParserError: failed at splitting arguments, either an unbalanced jinja2 block or quotes: /Users/ssbarnea/rdo/harem/contribs/kubespray/roles/download/tasks/download_{%

The code that makes ansible-lint choke can be found at https://github.com/kubernetes-sigs/kubespray/blob/55aa58ee2efa7ef00dd903706cffcf11b14a864b/roles/download/tasks/main.yml#L7

I found this while trying to enable ansible-lint on that repository.

Содержание

  1. The Ansible/Jinja parser incorrectly tries to parse command/shell comment blocks #28674
  2. Comments
  3. Can’t use string containing » in multi-line win_shell #124
  4. Comments
  5. Backslash escaping logic appears to be wrong inside a Jinja template #38199
  6. Comments
  7. Ansible 1.7 traceback in loading playbooks #8481
  8. Comments
  9. Ansible 1.7 traceback in loading playbooks #8481
  10. Comments

The Ansible/Jinja parser incorrectly tries to parse command/shell comment blocks #28674

ISSUE TYPE
COMPONENT NAME
ANSIBLE VERSION
CONFIGURATION
OS / ENVIRONMENT
SUMMARY

The Ansible/Jinja parser incorrectly tries to parse/match unrelevant quotes in the command or shell commands.

STEPS TO REPRODUCE
EXPECTED RESULTS

An Ansible command or shell task should not crash because we are using proper grammar in comments.

ACTUAL RESULTS

The text was updated successfully, but these errors were encountered:

Maintainers, what do you think of adding a boolean for inside_comment in ansible/lib/ansible/parsing/splitter.py when check_raw is True , and not modifying inside_quotes if we’ve hit a # sign and are thus inside a comment? I don’t know the implications of trying to convert everything to a raw string, which is the only other option coming to mind.

That reminds me, I tried using the <% raw %>Jinja directive in the task but the issue still reproduced.

I’m taking a fresher look at splitter.py and dealing with Jinja comment block depths is going to make things trickier. If these were passed as-is to the shell, we could look for an un-escaped # and break out of the inner for-loop.

Whats the use case for that? Is there an example of where/when this caused a problem in practice?

(Note: not claiming it’s not a bug or shouldn’t be fixed, just curious how this comes into play. )

@alikins there’s no use case for that, it’s just the easiest way to reproduce the issue.

The problem manifested itself when we were migrating legacy shell scripts verbatim to shell tasks (we plan on iteratively split them as proper ansible tasks later). One of the scripts had there’s in one of the comments and I lost a significant amount of time trying to figure out where the syntax error was.

Whats the use case for that? Is there an example of where/when this caused a problem in practice?

(Note: not claiming it’s not a bug or shouldn’t be fixed, just curious how this comes into play. )

I just had this issue where I was using bash comments in an Ansible task. Removing the ‘ from one of my comments resolved the issue. Don’t know how I would have figured it out without this issue! Thanks!

PR #28694 submitted by @nrwahl2 was closed.
While I can understand the ‘why put comments in your win_shell tasks’ argument, doing nothing leaves Ansible in a state where it breaks unexpectedly and without a clear error message as to why.

That PR was closed by the author because he was having trouble getting the integration tests to pass properly. Feel free to create your own PR that solves the problem in some way. This issue is still open because it has been acknowledged as a legitimate problem, even if it’s silly to try to do it in the first place.

The real problem is that the place in the code where this is happening is not specific to the command/shell modules (and in fact happens before any values are passed to the command/shell modules), and any fix can have unexpected side effects for other modules. The older-style key=value argument parsing can be brittle, and this is why the YAML args syntax exists and is preferred. That syntax would probably be deprecated/removed if it wasn’t required for ad-hoc commands.

Источник

Can’t use string containing » in multi-line win_shell #124

SUMMARY

When using a multi-line win_shell command, such as:

ansible-playbook fails with:

ISSUE TYPE
COMPONENT NAME
ANSIBLE VERSION
CONFIGURATION
OS / ENVIRONMENT

Target is Windows Server 2019 Standard (1809).
Connecting with WinRM.

STEPS TO REPRODUCE
EXPECTED RESULTS
ACTUAL RESULTS

The text was updated successfully, but these errors were encountered:

I tried to workaround with various combinations of escaping, but always got the same error if there was a followed by » anywhere. Changing » to ‘ did not help.

As a workaround I did this:

There’s definitely some weirdness in using multi-line strings in the parser (I don’t think this is related to win_shell , it would happen with anything, even just a var definition). For example, you can’t have comments (starting with # ) in the multi-line string either. I wasted an hour on that the other day.

If you’re not doing any jinja templating in the string (using << >> ) (or actually, maybe even if you are it doesn’t matter because ansible/ansible#4638) you can mark it as raw for jinja purposes, which is how I worked around the weirdness.

That may be a better workaround for your use case; I’m certainly going to keep it in mind whenever I’m pasting existing scripts into win_shell . Give it a try!

Yea this is definitely not an issue with win_shell but rather how Ansible parses a raw string in a module. It is trying to handle the older style of module args like — win_shell: Test-Function chdir=C:Windows . Unfortunately there are some false positives when it comes to interpreting quotes, especially ones after . There’s probably some more things we can do to make it better but this should be reported in ansible/ansible as that is where the parsing is happening.

I thought this was already a reported issue but I can’t seem to find it right now so will keep this open until I do or have opened a new issue for it.

Just a heads up: Using <% raw %>/ <% endraw %>as given above doesn’t resolve the issue for me 😞

The only workaround I know when you have a string that contains » is to template the backslash like so

Not ideal but it works because Ansible parses the value first to scan for module args before templating the values.

Источник

Backslash escaping logic appears to be wrong inside a Jinja template #38199

ISSUE TYPE
COMPONENT NAME
ANSIBLE VERSION
CONFIGURATION
OS / ENVIRONMENT
SUMMARY

Backslash escaping logic appears to be wrong inside a Jinja template. Trying to use a string that ends with a backslash in a template may fail.

STEPS TO REPRODUCE

Execute the following playbook.

Background: I’m dealing with Windows hosts and in one of my playbook I want to concatenate some variables with a single backslash as part of a conditional statement in a Jinja template.

EXPECTED RESULTS

I expect to have a proper way to include a string that ends with a backslash inside a Jinja template.

ACTUAL RESULTS

I can’t find such a way. It looks like the escaping logic (after any escaping done at the YAML parsing level) fails if a literal string ends with .

NOTES:

  • I already know that I can work around the issue by splitting into more tasks and using when . I’m simply reporting what I think is an issue.
  • I’m somewhat new to this so maybe I am missing something important. I hope not so I don’t waste anyone’s time.
  • In any case, if you think there is a better way to do this, I would be interested to know what it is and why I should be using it (if you can afford the time to explain).

OUTPUT:

The text was updated successfully, but these errors were encountered:

Источник

Ansible 1.7 traceback in loading playbooks #8481

I get this exception:

Traceback (most recent call last):
File «/usr/local/python_env/bin/ansible-playbook», line 309, in
sys.exit(main(sys.argv[1:]))
File «/usr/local/python_env/bin/ansible-playbook», line 249, in main
pb.run()
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/init.py», line 293, in run
play = Play(self, play_ds, play_basedir, vault_password=self.vault_password)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 153, in init
self._tasks = self._load_tasks(self._ds.get(‘tasks’, []), load_vars)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 589, in _load_tasks
loaded = self._load_tasks(data, mv, default_vars, included_sudo_vars, list(included_additional_conditions), original_file=include_filename, role_name=new_role)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 589, in _load_tasks
loaded = self._load_tasks(data, mv, default_vars, included_sudo_vars, list(included_additional_conditions), original_file=include_filename, role_name=new_role)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 597, in _load_tasks
role_name=role_name
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/task.py», line 238, in init
tokens = split_args(self.action)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/module_utils/splitter.py», line 163, in split_args
raise Exception(«error while splitting arguments, either an unbalanced jinja2 block or quotes»)
Exception: error while splitting arguments, either an unbalanced jinja2 block or quotes

The text was updated successfully, but these errors were encountered:

Thanks for filing a ticket! I am the friendly GitHub Ansibot. I see you did not fill out your issue description based on our new issue template. Please copy the contents of this template and paste it into the description of your ticket.

Our system will automatically close tickets that do not have an issue template filled out within 7 days. Please note that due to large interest in Ansible, humans may not comment on your ticket if you ask them questions. Don’t worry, you’re still in the queue and the robots are looking after you.

Tracebacks are always bad and we strive to handle those things correctly.

Most likely this is a formatting error, where our message needs to be improved.

We’re going to need to see your playbook to understand what’s causing this though, and can hopefully help you track down the formatting issue as well.

Would it be possible to provide the playbook?, ideally filed down to be as small as possible as a reproducer, as we may lack all the pieces of your environment to run it locally.

Источник

Ansible 1.7 traceback in loading playbooks #8481

I get this exception:

Traceback (most recent call last):
File «/usr/local/python_env/bin/ansible-playbook», line 309, in
sys.exit(main(sys.argv[1:]))
File «/usr/local/python_env/bin/ansible-playbook», line 249, in main
pb.run()
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/init.py», line 293, in run
play = Play(self, play_ds, play_basedir, vault_password=self.vault_password)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 153, in init
self._tasks = self._load_tasks(self._ds.get(‘tasks’, []), load_vars)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 589, in _load_tasks
loaded = self._load_tasks(data, mv, default_vars, included_sudo_vars, list(included_additional_conditions), original_file=include_filename, role_name=new_role)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 589, in _load_tasks
loaded = self._load_tasks(data, mv, default_vars, included_sudo_vars, list(included_additional_conditions), original_file=include_filename, role_name=new_role)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/play.py», line 597, in _load_tasks
role_name=role_name
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/playbook/task.py», line 238, in init
tokens = split_args(self.action)
File «/usr/local/python_env/lib/python2.6/site-packages/ansible/module_utils/splitter.py», line 163, in split_args
raise Exception(«error while splitting arguments, either an unbalanced jinja2 block or quotes»)
Exception: error while splitting arguments, either an unbalanced jinja2 block or quotes

The text was updated successfully, but these errors were encountered:

Thanks for filing a ticket! I am the friendly GitHub Ansibot. I see you did not fill out your issue description based on our new issue template. Please copy the contents of this template and paste it into the description of your ticket.

Our system will automatically close tickets that do not have an issue template filled out within 7 days. Please note that due to large interest in Ansible, humans may not comment on your ticket if you ask them questions. Don’t worry, you’re still in the queue and the robots are looking after you.

Tracebacks are always bad and we strive to handle those things correctly.

Most likely this is a formatting error, where our message needs to be improved.

We’re going to need to see your playbook to understand what’s causing this though, and can hopefully help you track down the formatting issue as well.

Would it be possible to provide the playbook?, ideally filed down to be as small as possible as a reproducer, as we may lack all the pieces of your environment to run it locally.

Источник

#ansible #hana

Вопрос:

Я пишу сценарий, который должен изменить пользователей всех Арендаторов базы данных. Когда я печатаю команду и выполняю ее вручную на Сервере, она работает нормально. С помощью командного модуля я получаю эту странную ошибку:

 ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: {{ _hdbclient }} -U BASIS_{{ SID }}_{{ item.item }} -x -a "{{ item.stdout | replace('"', '')}}" 
The error appears to be in '/tmp/awx_313202_z7e4l568/project/ansible_labor/scripts/update_users.yml': line 37, column 5, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Execute Querys on Tenants
  ^ here
 

Я думаю, что это как-то связано с кавычками в Командном модуле.
Это сценарий:

 ---
- name: Update all Users in DB
  hosts: '*'
  become: true
  vars:
    _User: "{{ lookup('env', 'USER') | upper }}_M"
    _pattern: ^"[a-zA-Z0-9]*"
    _tenants: []
    _query: select 'alter user ' || user_name || ' IDENTIFIED EXTERNALLY AS ''' || user_name ||'@INTERN'';' as todo from users where EXTERNAL_IDENTITY LIKE '%COMPANY.DE';
    _hdbclient: "/hana/shared/{{ SID }}/hdbclient/hdbsql -i {{ Instanz }} -n {{ inventory_hostname }}"
  tasks:
  - name: "Tenants der DB auslesen"
    command: "{{ _hdbclient }} -U BASIS_{{ SID }}_SYSTEMDB -x -a 'SELECT * FROM M_DATABASES'"
    register: tenants

  - debug:
      msg: "{{ tenants }}"

  - set_fact: 
      _tenants: "{{ _tenants    [ item | regex_search(_pattern) | replace('"', '') ] }}"
    with_items: "{{ tenants.stdout_lines }}"


  - name: Print extracted Tenants
    debug: 
      msg: "{{ _tenants }}"

  - name: Create Query on Tenant
    command: '{{ _hdbclient }} -U BASIS_{{ SID }}_{{ item }} -x -a "{{ _query }}"'
    register: query_tenants
    with_items: "{{ _tenants }}"

  - name: Print All Queries
    debug:
      msg: "{{ query_tenants.results[1] }}"

  - name: Execute Querys on Tenants
    command: "{{ _hdbclient }} -U BASIS_{{ SID }}_{{ item.item }} -x -a "{{ item.stdout | replace('"', '')}}" "
    with_items: "{{ query_tenants.results }}"
 

Ответ №1:

Это проблема с выходом из вашего replace фильтра. Вам нужно заменить двойные кавычки, которые переводятся как строка на " . Поскольку эта строка сама по себе находится внутри строки в двойных кавычках, вам нужно избежать escape => n

Так что, сохраняя ваше первоначальное цитирование, это дает:

     command: "{{ _hdbclient }} -U BASIS_{{ SID }}_{{ item.item }} -x -a "{{ item.stdout | replace('"', '') }}""
 

Между тем, есть несколько (неисчерпывающий список) альтернатив, которые вы, возможно, захотите рассмотреть:

     command: '{{ _hdbclient }} -U BASIS_{{ SID }}_{{ item.item }} -x -a "{{ item.stdout | replace(""", "") }}"'

    command: >-
      {{ _hdbclient }} -U BASIS_{{ SID }}_{{ item.item }} -x -a "{{ item.stdout | replace(""", "") }}"
 

Сопровождающие, что вы думаете о добавлении логического значения для inside_comment в ansible/lib/ansible/parsing/splitter.py когда check_raw равно True , и не изменять inside_quotes если мы попали в знак # и оказались внутри комментария? Я не знаю последствий попытки преобразовать все в необработанную строку, это единственный другой вариант, который приходит на ум.

Это напомнило мне, что я пытался использовать в задаче директиву Jinja {% raw%}, но проблема все равно воспроизводилась.

Я по-новому смотрю на splitter.py и работа с глубиной блока комментариев Jinja может усложнить задачу. Если бы они были переданы оболочке как есть, мы могли бы искать неэкранированный # и выйти из внутреннего цикла for.

@dmsimard : я отправил PR № 28694


ansible localhost -m shell -a "# there's a comment block"

Какой для этого вариант использования? Есть ли на практике пример того, где / когда это вызвало проблему?

(Примечание: не утверждать, что это не ошибка или не следует исправлять, просто любопытно, как это вступает в игру …)

Что-то что-то динамическое? ;)

Отправлено с мобильного телефона ProtonMail

——— Исходное сообщение ———
28 августа 2017 года в 10:20 Адриан Ликинс написал:

ansible localhost -m shell -a «# есть блок комментариев»

Какой для этого вариант использования? Есть ли на практике пример того, где / когда это вызвало проблему?

(Примечание: не утверждать, что это не ошибка или не следует исправлять, просто любопытно, как это вступает в игру …)


Вы получили это, потому что оставили комментарий.
Ответьте на это письмо напрямую, просмотрите его на GitHub или отключите чат .

@alikins для этого нет

Проблема проявилась, когда мы дословно переносили устаревшие сценарии оболочки в задачи оболочки (позже мы планируем итеративно разделять их как подходящие задачи). В одном из сценариев в одном из комментариев было there's и я потерял значительное количество времени, пытаясь выяснить, где была синтаксическая ошибка.

ansible localhost -m shell -a "# there's a comment block" 

Какой для этого вариант использования? Есть ли на практике пример того, где / когда это вызвало проблему?

(Примечание: не утверждать, что это не ошибка или не следует исправлять, просто любопытно, как это вступает в игру …)

У меня была эта проблема, когда я использовал комментарии bash в задаче Ansible. Удаление ' из одного из моих комментариев решило проблему. Не знаю, как бы я понял это без этой проблемы! Благодаря!

PR № 28694, представленный @ nrwahl2, был закрыт.
Хотя я могу понять аргумент «зачем помещать комментарии в ваши задачи win_shell», ничего не делая, оставляя Ansible в состоянии, когда он неожиданно ломается и без четкого сообщения об ошибке, почему.

Этот PR был закрыт автором, потому что у него возникли проблемы с правильным прохождением интеграционных тестов. Смело создавайте собственный пиар, который каким-то образом решает проблему. Эта проблема все еще остается открытой, потому что она была признана законной, даже если вообще глупо пытаться ее решить.

Настоящая проблема заключается в том, что место в коде, где это происходит, не является специфическим для модулей команды / оболочки (и фактически происходит до того, как какие-либо значения будут переданы в модули команды / оболочки), и любое исправление может иметь неожиданные побочные эффекты для другие модули. Синтаксический анализ аргумента ключ = значение в старом стиле может быть хрупким, поэтому синтаксис аргументов YAML существует и предпочтителен. Этот синтаксис, вероятно, был бы устаревшим / удален, если бы он не требовался для специальных команд.

Меня недавно укусила эта проблема, и я потратил добрых два часа, пытаясь понять ее, прежде чем нашел это. В моем случае это произошло потому, что у нас была куча задач с блоками, использующими записи shell: для определения своих сценариев, и один из этих сценариев оболочки был изменен, чтобы добавить несколько полезных комментариев, объясняющих, что он делал:

- name: install FOO
  block:
    - name: Create admin user
      args:
        executable: /bin/bash
      shell: |
        #!/bin/bash
        set -e
        admin_user="${ADMIN_USER}"
        admin_role="${ADMIN_ROLE}"
        admin_pwd="${ADMIN_PWD}"

        # Do some stuff
        some_stuff 'foo' 'bar' 'baz'

        # We can't use the normal create-user endpoint, because it requires authentication and we don't have a user to authenticate as yet
        docker exec foo-ms curl 
          -X 'POST' 
          -H 'Content-Type: application/json' 
          -d"{"username": "${admin_user}", "role_id": "${admin_role}", "fullname": "user administrator", "password": "${admin_pwd}"}" 
          'http://localhost/defaults/admin' 
          2>&1

        # Do other stuff
        other_stuff 'zip' 'zap'

Проблема, конечно, в том комментарии посередине, в котором есть слово «не могу», поэтому, если кому-то интересно, почему у кого-то могут быть комментарии в блоках оболочки, вот пример.

Вы, вероятно, можете обойти это, используя args.cmd вместо «сырого» формата параметров.

- name: install FOO
  block:
    - name: Create admin user
      shell:
      args:
        executable: /bin/bash
        cmd: |
          #!/bin/bash
          set -e
          admin_user="${ADMIN_USER}"
          admin_role="${ADMIN_ROLE}"
          admin_pwd="${ADMIN_PWD}"

          # Do some stuff
          some_stuff 'foo' 'bar' 'baz'

          # We can't use the normal create-user endpoint, because it requires authentication and we don't have a user to authenticate as yet
          docker exec foo-ms curl 
            -X 'POST' 
            -H 'Content-Type: application/json' 
            -d"{"username": "${admin_user}", "role_id": "${admin_role}", "fullname": "user administrator", "password": "${admin_pwd}"}" 
            'http://localhost/defaults/admin' 
            2>&1

          # Do other stuff
          other_stuff 'zip' 'zap'

@agaffney Я уже работал над этим, изменив слово на «не могу». Но это все еще проблема, которой никогда не должно было случиться, и она усугублялась неинформативным и вводящим в заблуждение сообщением об ошибке.

Известно, что старый синтаксический анализатор key=value используемый для обработки аргументов произвольной формы для модулей, имеет подобные недостатки, и вы не можете исправить его, не нарушив его для вещей, которые раньше работали. Это cmd из причин, по которым были введены синтаксис аргументов YAML и shell .

Просто зарегистрировавшись, я также столкнулся с этой проблемой в Ansible версии 2.9.15.

Была ли эта страница полезной?

0 / 5 — 0 рейтинги

SUMMARY

When using a multi-line win_shell command, such as:

 - name: Enable basic auth
      ansible.windows.win_shell: |
        Import-Module WebAdministration
        $IISPath = "IIS:"
...

ansible-playbook fails with:

ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes:
ISSUE TYPE
  • Bug Report
COMPONENT NAME

Module ansible.windows.win_shell.

ANSIBLE VERSION
ansible 2.10.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/dave/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/dave/.local/lib/python3.6/site-packages/ansible
  executable location = /home/dave/.local/bin/ansible
  python version = 3.6.9 (default, Oct  8 2020, 12:12:24) [GCC 8.4.0]
CONFIGURATION
DEFAULT_VAULT_PASSWORD_FILE(env: ANSIBLE_VAULT_PASSWORD_FILE) = /home/dave/code/ops/.vault_pass.txt
OS / ENVIRONMENT

Target is Windows Server 2019 Standard (1809).
Connecting with WinRM.

 $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      17763  1432
STEPS TO REPRODUCE
 - name: Enable basic auth
      ansible.windows.win_shell: |
        $ErrorActionPreference = "Stop"
        Import-Module WebAdministration
        $IISPath = "IIS:"
        $FTPUserGroupName = "FTP Users"
        $FTPSiteName = 'FTP Site'
        $FTPSitePath = "IIS:Sites$FTPSiteName"
        $BasicAuth = 'ftpServer.security.authentication.basicAuthentication.enabled'
        Set-ItemProperty -Path $FTPSitePath -Name $BasicAuth -Value $True
        $Param = @{
            Filter   = "/system.ftpServer/security/authorization"
            Value    = @{
                accessType  = "Allow"
                roles       = "$FTPUserGroupName"
                permissions = 1
            }
            Location = $FTPSiteName
            PSPath = $IISPath
        }
        Add-WebConfiguration @param
        echo $null >> C:ftp.ansible_statebasic_auth
      args:
        creates: C:ftp.ansible_statebasic_auth
EXPECTED RESULTS

Task completes.

ACTUAL RESULTS
$ ansible-playbook -i hosts.yml -l ftp_servers deploy.yml 
ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: $ErrorActionPreference = "Stop"
Import-Module WebAdministration
$IISPath = "IIS:"
$FTPUserGroupName = "FTP Users"
$FTPSiteName = 'FTP Site'
$FTPSitePath = "IIS:Sites$FTPSiteName"
$BasicAuth = 'ftpServer.security.authentication.basicAuthentication.enabled'
Set-ItemProperty -Path $FTPSitePath -Name $BasicAuth -Value $True
$Param = @{
    Filter   = "/system.ftpServer/security/authorization"
    Value    = @{
        accessType  = "Allow"
        roles       = "$FTPUserGroupName"
        permissions = 1
    }
    Location = $FTPSiteName
    PSPath = $IISPath
}
Add-WebConfiguration @param
echo $null >> C:ftp.ansible_statebasic_auth


The error appears to be in '/home/dave/code/ops/deploy.yml': line 116, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


    - name: Enable basic auth
      ^ here

Понравилась статья? Поделить с друзьями:
  • Error failed building wheel for wxpython
  • Error fail to run the game
  • Error failed building wheel for scikit learn
  • Error fail to hook gettickcount metal gear solid v ground zeroes
  • Error failed building wheel for pyzmq