在 Ansible 中进行案例陈述的最佳方法是什么?



我正在尝试将我的脚本转换为 Ansible 以实现自动化。我陷入了理解循环或"with_items"用例的困境。

原始 bash 脚本:

for i in apple banana orange; do
case $i in
apple) export var="var.1:apple1,var.2:apple2" ;;
banana) export var="var.1:banana1,var.2:banana2,var.3:banana3" ;;
orange) export var="var.1:orange1" ;;
esac
echo "$i"

到目前为止我尝试过:

VARS file:
fruits:
- name: apple
var: "{{ item }}"
with_items:
- apple1
- apple2
- name: banana
var: "{{ item }}"
with_items:
- banana1
- banana2
- banana3
- name: orange
var: "{{ item }}"
with_items:
- orange1
TASKS file:
- include_vars: vars.yml
- debug:
msg: "{{ fruits }}"
- name: output in shell using echo 
shell: |
echo "{{ fruits.name }}" ;
echo "{{ fruits.var }}"
loop: "{{ fruits }}"

输出:

The output from include_vars task:
{
"ansible_included_var_files": [
"/etc/ansible/roles/openssl/tasks/vars.yml"
],
"ansible_facts": {
"fruits": [
{
"var": "{{ item }}",
"name": "apple",
"with_items": [
"apple1",
"apple2"
]
},
{
"var": "{{ item }}",
"name": "banana",
"with_items": [
"banana1",
"banana2",
"banana3"
]
},
{
"var": "{{ item }}",
"name": "orange",
"with_items": [
"orange1"
]
}
]
},
"_ansible_no_log": false,
"changed": false
}

调试

debug task failed
{
"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefinednnThe error appears to be in '/etc/ansible/roles/openssl/tasks/main.yml': line 262, column 3, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nnn- debug:n  ^ heren",
"_ansible_no_log": false
}

我知道Yaml对空间敏感,格式化很重要。我是编写剧本的新手,任何指示都会有所帮助。

使用字典

fruits:
apple:
- apple1
- apple2
banana:
- banana1
- banana2
- banana3
orange:
- orange1

循环

- hosts: localhost
tasks:
- include_vars:
vars.yml
- debug:
msg: "{{ item.key }} {{ item.value }}"
loop: "{{ fruits|dict2items }}"

给予(删节(

"msg": "orange [u'orange1']"
"msg": "apple [u'apple1', u'apple2']"
"msg": "banana [u'banana1', u'banana2', u'banana3']"

可以引用字典中的项目。例如

- debug:
var: fruits.banana
- debug:
var: fruits.apple.1

"fruits.banana": [
"banana1", 
"banana2", 
"banana3"
]
"fruits.apple.1": "apple2"

相关内容

最新更新