我需要在ansible中使用循环显示当前的java版本。目前我能够在主机服务器上获取并显示相同内容,但是当我需要在另一个播放中传递相同的值时,它在那里不起作用。 以下是剧本 - 问题是在localhost播放中究竟需要更改的内容,以便我们可以获取java版本的值,并且在将来如果我们添加或删除任何主机服务器,在这种情况下,必须不需要编码更改,因为它必须是在循环中。
Host inventory -
[testserver]
zlp12037 ansible_ssh_host=zlp12037.vci.att.com ansible_ssh_user=abc
zlp12036 ansible_ssh_host=zlp12036.vci.att.com ansible_ssh_user=abc
---
- hosts: testserver
tasks:
- name: Fetch Java Version
shell: java -version 2>&1 | grep version | awk '{print $3}' | sed 's/"//g'
register: result
- debug: msg="{{item}}:{{result.stdout}}"
with_items: "{{ inventory_hostname }}"
- hosts: localhost
tasks:
- debug: var=hostvars['item']['result']['stdout']
with_items: groups['inventory_hostname']
Result:
TASK [Fetch Java Version] ******************************************************
changed: [zlp12037]
changed: [zlp12036]
TASK [debug] *******************************************************************
ok: [zlp12037] => (item=zlp12037) => {
"item": "zlp12037",
"msg": "zlp12037:1.8.0_66"
}
ok: [zlp12036] => (item=zlp12036) => {
"item": "zlp12036",
"msg": "zlp12036:1.8.0_66"
}
PLAY [localhost] ***************************************************************
TASK [setup] *******************************************************************
ok: [localhost]
TASK [debug] *******************************************************************
ok: [localhost] => (item=groups['inventory_hostname']) => {
"hostvars['item']['result']['stdout']": "VARIABLE IS NOT DEFINED!",
"item": "groups['inventory_hostname']"
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
zlp12036 : ok=3 changed=1 unreachable=0 failed=0
zlp12037 : ok=3 changed=1 unreachable=0 failed=0
答案 0 :(得分:1)
with_items
必须模板化object['item']
使用文字名称item
获取项目,而object[item]
从名为item
的变量获取名称项目groups[inventory_hostname]
会尝试在您的案例中找到名为localhost
的群组我想,你想:
- hosts: localhost
tasks:
- debug: var=hostvars[item]['result']['stdout']
with_items: "{{ groups['testserver'] }}"
答案 1 :(得分:0)
您可以运行一个bash脚本来执行并将Java版本值存储在一个文件中,您可以在ansible playbook中阅读该文件。
https://stackoverflow.com/a/7335524/7328096
if type -p java; then
echo found java executable in PATH
_java=java
elif [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]];
then
echo found java executable in JAVA_HOME
_java="$JAVA_HOME/bin/java"
else
echo "no java"
fi
if [[ "$_java" ]]; then
version=$("$_java" -version 2>&1 | awk -F '"' '/version/
{print $2}')
echo version "$version"
if [[ "$version" > "1.5" ]]; then
echo version is more than 1.5
else
echo version is less than 1.5
fi
fi