大网数据广告活动
服务器运维问答

Variables in Ansible ad hoc commands

· 52CE 我爱测

Question: How can I evaluate (extra-)variables inside an ad-hoc command? Is there a way to make arrays work inside ad-hoc commands? Background: I want to ensure that multiple containers on a host are running (in my example this i…

问题原文

原帖链接 · MacMartin · CC BY-SA 4.0

Question:

How can I evaluate (extra-)variables inside an ad-hoc command?

Is there a way to make arrays work inside ad-hoc commands?

Background: I want to ensure that multiple containers on a host are running (in my example this is "test01" and "test02")

I already found out (please correct me if I'm wrong) that I can't use an array or with_items in adhoc commands, so that doesn't work:

ansible all -i ,localhost -m docker_container -c local -a 'name=["test01","test02"] state=started command="sleep infinity"

Now I tried, but also didn't work:

ansible all -i ,localhost -m docker_container -c local -e MYVAR='[test01,test02]' -a 'name=MYVAR state=started command="sleep infinity"

... or even ...

ansible all -i ,localhost -m shell -c local -e MYVAR='[test01,test02]' -a 'echo MYVAR'

Or is the -e (--extra-vars) parameter wrong?

(Environment: ansible 2.9.10 on linux (manjaro) )

已采纳解答

原帖链接 · Gerald Schneider · CC BY-SA 4.0

The same as in any playbook or variable file, using curly braces:

ansible all -i ,localhost -m shell -c local -e MYVAR='[test01,test02]' -a 'echo {{ MYVAR }}'

Though I don't get the point of doing this, you can just use the value of the variable where you need it directly ...

This will also not help you in looping over lists, it depends entirely on the module if it supports multiple values in a parameter or not, if not you will have to implement the loop in a shell script.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-07-28)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。