由于错误的引号 Ansible,拆分参数时出错

Error with splitting Arguments due to bad quotes Ansible

我正在写一个脚本,它应该改变数据库所有租户的用户。当我打印命令并在服务器上手动执行它时,它工作正常。使用命令模块我得到这个奇怪的错误:

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 }}"

这是您的 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("\"", "") }}"