Ansible双引号和变量

时间:2018-02-24 10:56:17

标签: mysql json ansible escaping double-quotes

我尝试在stackoverflow上实现一个solution来截断数据库中的所有表。

当我在终端命令行上运行它时,它工作,但不幸的是它在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

添加了失败消息的输出

ansible output of fail message

1 个答案:

答案 0 :(得分:2)

使用shell而不是命令工作。

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