我有一个shell脚本,其输出是以下格式的回声
<variable_1>;<variable_2>;<variable_3>
等
我想使用这些变量并运行mysql查询来更新数据库,如此
mysql -u<user> -p<password> -h<host> -e'insert into test_table values ("variable_1","variable_2","variable_3")'
我的ansible剧本看起来像这样。
---
- hosts: infoServers
sudo: yes
gather_facts: no
tasks:
- name: gather info
script: get_hostdata.sh
register: result
- name: print result
local_action: command mysql -uuser -ppassword -h192.168.101.10 ansible_db -e'insert into test_table values ("{{ item[0] }}","{{ item[1] }}","{{ item[3] }});'
with_items: [ result.stdout.split(';')[0], result.stdout.split(';')[1], result.stdout.split(';')[2] ]
错误:加载YAML脚本时出现语法错误,test_variables.yml
基本上我希望能够使用shell命令的输出,将其拆分为一些变量,并能够在进一步的ansible动作中使用它们。 您能否指导我如何正确访问变量?
谢谢
答案 0 :(得分:5)
当您收到此类错误时,您应该提供错误消息的完整详细信息。当我将您的剧本剪切并粘贴到文件中并尝试运行它时,我得到以下内容:
ERROR: Syntax Error while loading YAML script, ff.yml
Note: The error may actually appear before this position: line 11, column 43
local_action: command mysql -uuser -ppassword -h192.168.101.10 ansible_db -e'insert into test_table values ("{{ item[0] }}","{{ item[1] }}","{{ item[3] }});'
with_items: [ result.stdout.split(';')[0], result.stdout.split(';')[1], result.stdout.split(';')[2] ]
^
所以看来,如果这与你收到的完整错误相符,你的with_items子句的语法是错误的。
我不确定为什么你甚至试图使用with_items来做这件事。在这种情况下你所做的只是一些不必要的变量替换。以下内容也应该完全符合您的要求:
- name: print result
local_action: command mysql -uuser -ppassword -h192.168.101.10 ansible_db -e'insert into test_table values ("{{ result.stdout.split(';')[0] }}","{{ result.stdout.split(';')[1] }}","{{ result.stdout.split(';')[2] }}");'
答案 1 :(得分:3)
您需要正确引用和使用{{}}
。
- hosts: localhost
tags: s16
gather_facts: no
tasks:
- shell: echo 'variable_1;variable_2;variable_3'
register: result
- local_action: debug msg="values ("{{ item[0] }}","{{ item[1] }}","{{ item[3] }}");'"
with_items: [ "{{result.stdout.split(';')[0]}}", "{{result.stdout.split(';')[1]}}", "{{result.stdout.split(';')[2]}}" ]
会打印出类似的内容:
TASK: [debug msg="values ("{{ item[0] }}","{{ item[1] }}","{{ item[3] }}");'"] ***
ok: [localhost -> 127.0.0.1] => (item=variable_1) => {
"item": "variable_1",
"msg": "values (\"v\",\"a\",\"i\");'"
}
ok: [localhost -> 127.0.0.1] => (item=variable_2) => {
"item": "variable_2",
"msg": "values (\"v\",\"a\",\"i\");'"
}
ok: [localhost -> 127.0.0.1] => (item=variable_3) => {
"item": "variable_3",
"msg": "values (\"v\",\"a\",\"i\");'"
}
正如您在item[0], .., item[2]
中看到的那样,您正在索引字符串"variable_1"
而不是数组["variable_1","variable_2","variable_3"]
最简单(以及更高性能)的方法是:
- hosts: localhost
tags: s17
gather_facts: no
tasks:
- shell: echo 'variable_1;variable_2;variable_3'
register: result
- debug: msg="insert into tt values ("{{result.stdout|replace(';', '","')}}");'"