关于YAML(ansible)中嵌套变量的问题

huangapple go评论93阅读模式
英文:

Issue with nested variables in YAML (ansible)

问题

我在使用YAML格式的变量时遇到了问题。

我正在尝试在同一个任务中使用Ansible为x86_64和s390x平台安装软件包:

vars:
  x86_64_pckg:
    - p1
    - p2
    - p3
  s390x_pckg:
    - p4
    - p5
  
name: 安装备份工具
yum:
  name: "{{ {{ ansible_architecture }}_pckg }}"
  state: latest

我认为问题出在引号上。但也许只能通过创建两个任务并使用when:条件来处理不同的架构来解决我的问题。

英文:

I'm facing an issue when playing with variables in YAML format

I'm trying in the same task to install packages for both x86_64 and s390x platform with ansible :

vars:
  x86_64_pckg:
    - p1
    - p2
    - p3
  s390x_pckg:
    - p4
    - p5
  
name: install backup tool
yum:
  name: "{{ {{ ansible_architecture }}_pckg }}"
  state: latest

I'm struggling with the quotes I think. But maybe my issue could only be resolved by creating two tasks and using the when: condition for managing the different architectures

答案1

得分: 2

如果你想要处理嵌套变量,你应该使用 ansible.builtin.vars 查找。

所以,如果你将

"{{ {{ ansible_architecture }}_pckg }}"

改为

"{{ lookup('ansible.builtin.vars', ansible_architecture + '_pckg') }}"

你将能够创建一个嵌套变量。

更多信息请查阅文档:https://docs.ansible.com/ansible/latest/collections/ansible/builtin/vars_lookup.html

英文:

If you want to work with nested variables you should use ansible.builtin.vars lookup.

So, if you change

"{{ {{ ansible_architecture }}_pckg }}"

to

"{{ lookup('ansible.builtin.vars', ansible_architecture + '_pckg') }}"

you'll be able to make a nested variable.

Documentation for more info: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/vars_lookup.html

答案2

得分: 1

将哈希值放入字典中。然后,使用方法很简单

vars:

  pkg:
    x86_64: [p1, p2, p3]
    s390x: [p4, p5]

tasks:
  
  - yum:
      name: "{{ pkg[ansible_architecture] }}"
      state: latest
英文:

Put the hashes into a dictionary. Then, the usage is trivial

vars:

  pkg:
    x86_64: [p1, p2, p3]
    s390x: [p4, p5]

tasks:
  
  - yum:
      name: "{{ pkg[ansible_architecture }}"
      state: latest

huangapple
  • 本文由 发表于 2023年7月10日 20:47:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定