Ansible 双引号和变量

Ansible double quotes and variables

我正在尝试实现一个 solution 我在 Whosebug 上找到的 运行cating 数据库中的所有表。

当我在终端命令行上 运行 它时它可以工作,但不幸的是它在 Ansible 上不起作用。

有问题的部分是 -e \"truncate table $table\" 我应该如何处理双引号中的变量?到目前为止我找不到任何解决方案。

- set_fact: db_truncate_command="mysql -v -h {{ wp_db_host }} -u {{ wp_db_user }} -p{{ wp_db_password }} -Nse 'show tables' {{ wp_db_name }} | while read table; do mysql -v -h {{ wp_db_host }} -u {{ wp_db_user }} -p{{ wp_db_password }}  -e \"truncate table $table\" {{ wp_db_name }}; done"
  when: stat_db_file.stat.exists

- debug:
    msg: "command {{ db_truncate_command }} "

- name: Truncate existing tables in db
  command: >
    {{ db_truncate_command }}
  when: stat_db_file.stat.exists

我得到的输出:

TASK [mysql : set_fact] ***********************************************************************************************************************************************************
ok: [ansible.mydomain.com] => {"ansible_facts": {"db_truncate_command": "mysql -v -h 192.155.190.255 -u wp_user -pMyPassword -Nse 'show tables' ansible | while read table; do mysql -v -h 192.155.190.255 -u wp_user -pMyPassword  -e \"truncate table $table\" ansible; done"}, "changed": false}

TASK [mysql : debug] **************************************************************************************************************************************************************
ok: [ansible.mydomain.com] => {
    "msg": "command mysql -v -h 192.155.190.255 -u wp_user -pMyPassword -Nse 'show tables' ansible | while read table; do mysql -v -h 192.155.190.255 -u wp_user -pMyPassword  -e \"truncate table $table\" ansible; done "
}

TASK [mysql : Truncate existing tables in db] *************************************************************************************************************************************
fatal: [ansible.mydomain.com]: FAILED! => {"changed": true, "cmd": ["mysql", "-v", "-h", "192.155.190.255", "-u", "wp_user", "-pMyPassword", "-Nse", "show tables", "ansible", "|", "while", "read", "table;", "do", "mysql", "-v", "-h", "192.155.190.255", "-u", "wp_user", "-pMyPassword", "-e", "truncate table $table", "ansible;", "done"], "delta": "0:00:00.005262", "end": "2018-02-24 10:33:22.808490", "msg": "non-zero return code", "rc": 1, "start": "2018-02-24 10:33:22.803228", "stderr": "mysql: [Warning] Using a password on the command line interface can be insecure.", "stderr_lines": ["mysql: [Warning] Using a password on the command line interface can be insecure."], "stdout": "mysql  Ver 14.14 Distrib 5.7.21, for Linux (x86_64) using  EditLine wrapper\n

添加了失败消息的输出

使用 shell 代替命令有效。

- name: Truncate existing tables in db
  shell: >
    {{ db_truncate_command }}
  when: stat_db_file.stat.exists