How to get variables from ansible result

北城以北 提交于 2019-12-04 08:13:49

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] ]
                                          ^

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

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

You need to quote and use {{}} correctly.

- 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]}}" ]

Will print something like:

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

As you can see with item[0], .., item[2] you're indexing into the string "variable_1" instead of the array ["variable_1","variable_2","variable_3"]

Simplest (and a lot more performant) way to do this would be:

- 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(';', '","')}}");'"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!