Ansible Playbook Shell模块,转义特殊字符

时间:2018-12-07 17:01:39

标签: shell ansible

在ansible剧本中使用ansible 2.4.2.0

- name: Check the Tomcat version
  shell: "unzip -c {{ mount_path_instance }}/tomcat9/lib/catalina.jar META-INF/MANIFEST.MF |awk '/Implementation-Version: / {sub(/[^ ]+ /, \"\"); print \$0}'"
  register: tomcat_version
  when: instance_check_v9.stat.exists

我得到了错误

TASK [redhat-tomcat-update : include_tasks] ************************************
fatal: [localhost]: FAILED! => {"reason": "Syntax Error while loading YAML.\n\n\nThe error appears to have been in '/home/ansible/work/play_redhat_tomcat_update/roles/redhat-tomcat-update/tasks/variables.yml': line 39, column 153, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n- name: Check the Tomcat version\n  shell: \"unzip -c {{ mount_path_instance }}/tomcat9/lib/catalina.jar META-INF/MANIFEST.MF |awk '/Implementation-Version: / {sub(/[^ ]+ /, \\\"\\\"); print \\$0}'\"\n                                                                                                                                                        ^ here\nWe could be wrong, but this one looks like it might be an issue with\nmissing quotes.  Always quote template expression brackets when they\nstart a value. For instance:\n\n    with_items:\n      - {{ foo }}\n\nShould be written as:\n\n    with_items:\n      - \"{{ foo }}\"\n\nexception type: <class 'yaml.scanner.ScannerError'>\nexception: while parsing a quoted scalar\n  in \"<unicode string>\", line 39, column 10\nfound unknown escape character\n  in \"<unicode string>\", line 39, column 153"}

运行下一条命令可以正常工作

ansible localhost -m shell -a "unzip -c {{ mount_path_instance }}/tomcat9/lib/catalina.jar META-INF/MANIFEST.MF |awk '/Implementation-Version: / {sub(/[^ ]+ /, \"\"); print \$0}'" --extra-vars='{"mount_path_instance": "/appl/tomcat/paul_1_uat", "instance_name": "paul_1_uat" }'

[警告]:考虑使用非归档模块,而不是运行unzip

localhost |成功| rc = 0 >> 9.0.7.redhat-12

有人看到yml定义有什么问题吗?

1 个答案:

答案 0 :(得分:0)

YAML在双引号字符串中扩展反斜杠,并且\$不是YAML中的合法转义符(\"很好)

您想要的是使用替代双引号问题的替代语法:

shell: |
   unzip -c {{ mount_path_instance }}/tomcat9/lib/catalina.jar META-INF/MANIFEST.MF | awk '/Implementation-Version: / {sub(/[^ ]+ /, ""); print $0}'

具有讽刺意味的是,由于awk命令已经在单引号中了,因此您实际上不必逃脱$ sign,因此您也可以从现有命令中删除\$,但是我很确定使用shell: |语法,您将获得更少的反斜杠攻击


关于:

ansible localhost -m shell -a "unzip -c {{ mount_path_instance }}/tomcat9/lib/catalina.jar META-INF/MANIFEST.MF |awk '/Implementation-Version: / {sub(/[^ ]+ /, \"\"); print \$0}'"

运行良好,这是因为您的 shell 实际上为您折叠了\$,您可以通过简单的回声看到它:

echo "thingy \"\" \$0"