ansible - 如何获得以逗号分隔的名字列表?

标签 ansible yaml jinja2 ansible-template

这是我在 YAML 文件中的地址列表:

addresses:
  person1:
    firstname: Maria
    lastname:  Smith
  person2:
    firstname: July
    lastname:  Weber
  person3:
    firstname: John
    lastname:  Kurt
  person4:
    firstname: Simon
    lastname:  Gates

我需要的是逗号分隔的字符串,如 Maria, July, John, Simon

我尝试了以下方法:

firstnames: >-
  {% set lastnames_list= [] %}
  {% for name in addresses %}
      {{ name.firstname | join(",")}}
  {% endfor %}
  {{ lastnames_list }} 

firstnames: >-
  {% set lastnames_list= [] %}
  {% for name in addresses %}
      {{ name | map(attribute="firstname") | join(",") }}
  {% endfor %}
  {{ lastnames_list }} 

firstnames: '{{ addresses | map(attribute="firstname") | join(",") }}' 

但 Ansible 给出了以下输出:

The task includes an option with an undefined variable. The error was: 'unicode object' has no attribute 'firstname'

最佳答案

简单 json_query filter可用于实现结果。

- debug:
    msg: '{{ addresses | json_query("@.*.firstname") | join(", ") }}'

给予

ok: [localhost] => 
  msg: Maria, July, John, Simon

关于ansible - 如何获得以逗号分隔的名字列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62497040/

相关文章:

go - 如果我不知道使用 go 的(结构)中的预期模式,如何验证/读取 yaml?

ruby-on-rails - rake 数据库 :dump fails when specifying an environment

bash - 我可以向 Azure DevOps 中的现有变量组添加多个变量吗?

python - 狮身人面像添加背景图像

Ansible 从循环中拉出 block 设备 UUID,并用于挂载模块上的变量

yaml - ansible项目的ctags

amazon-web-services - Ansible:提供新分配的 ec2 实例

routing - Flask url_for 在模块化应用程序中路由时出错

docker - 如何在Docker容器中运行Ansible脚本

Ansible-Tower ssl : the specified credentials were rejected by the server