Ansible中的多行Shell脚本与Jinja变量

时间:2018-12-05 22:27:31

标签: shell ansible jinja2

我一直在追问这个问题How to do multiline shell script in Ansible,但是,在我有点复杂的示例中,此解决方案不起作用。我正在尝试使这部分YAML起作用:

- name: "set wifi country code to {{ wifi_country }}"
  shell: |
    list_wlan_interfaces() {
      for dir in /sys/class/net/*/wireless; do
        if [ -d "$dir" ]; then
          basename "$(dirname "$dir")"
        fi
      done
    }
    IFACE="$(list_wlan_interfaces | head -n 1)"
    wpa_cli -i "$IFACE" set country {{ wifi_country }}
    wpa_cli -i "$IFACE" save_config > /dev/null"

但是,我遇到了错误:

ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: list_wlan_interfaces() {
  for dir in /sys/class/net/*/wireless; do                          
    if [ -d "$dir" ]; then                                                    
      basename "$(dirname "$dir")"           
    fi                                                                                                                                 
  done                                                                                                                              
}                                                                                         
IFACE="$(list_wlan_interfaces | head -n 1)"                                                    
wpa_cli -i "$IFACE" set country {{ wifi_country }}
wpa_cli -i "$IFACE" save_config > /dev/null"

The error appears to have been in 'rpi.yml': line 7, column 5, but may
be elsewhere in the file depending on the exact syntax problem.                                                                                            

The offending line appears to be:

  tasks:                             
  - name: "set wifi country code to {{ wifi_country }}"
    ^ here                                  
We could be wrong, but this one looks like it might be an issue with                                  
missing quotes.  Always quote template expression brackets when they
start a value. For instance:                                                                                            

    with_items:
      - {{ foo }}                                  

Should be written as:                  

    with_items:                                                                       
      - "{{ foo }}"    

如何在Ansible剧本中放置包含Jinja变量的shell脚本?

1 个答案:

答案 0 :(得分:1)

这是一个非常令人误解的错误消息,但是您的问题实际上是/dev/null"末尾的双引号