如何从ansible结果中获取变量 [英] How to get variables from ansible result

查看:54
本文介绍了如何从ansible结果中获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 shell 脚本,它的输出是以下格式的回显
;;

I have a shell script whose output is an echo of the following format
<variable_1>;<variable_2>;<variable_3> etc

我想使用这些变量并运行一个 mysql 查询来更新这样的数据库
<代码>mysql -u<用户>-p<密码>-h<主机>-e'插入 test_table 值 ("variable_1","variable_2","variable_3")'

I want to use these variables and run a mysql query to update a DB like so
mysql -u<user> -p<password> -h<host> -e'insert into test_table values ("variable_1","variable_2","variable_3")'

我的 ansible 剧本是这样的.

My ansible playbook looks like this.

---
- 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 时出现语法错误

ERROR: Syntax Error while loading YAML script, test_variables.yml

基本上我希望能够使用 shell 命令的输出,将其拆分为一些变量,并能够在进一步的 ansible 操作中使用这些变量.你能指导我如何正确访问变量吗?

Basically i want to be able to use the output of a shell command, split it into some variables and be able to use those in further ansible actions. Can you please guide me on how to access the variables correctly?

谢谢

推荐答案

当您遇到这样的错误时,您确实应该提供错误消息的完整详细信息.当我将您的剧本剪切并粘贴到文件中并尝试运行它时,我得到以下信息:

When you get an error like this you really should provide the full details of the error message. When I cut and paste your playbook into a file and tried to run it I got the following:

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 子句的语法是错误的.

So it appears, if this matches up with the full error you were receiving that the syntax of your with_items clause is wrong.

我不知道你为什么要尝试使用 with_items 来做到这一点.在这种情况下,您所做的只是一些不必要的变量替换.以下内容也应该完全符合您的要求:

I'm not sure why you're even trying to do this using with_items. All you're effectively doing in this case is some unnecessary variable substitution. The following should also do exactly what you want:

- 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] }}");'

这篇关于如何从ansible结果中获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆