首页 > 解决方案 > ansible - 使用变量数组并循环遍历它

问题描述

我必须运行这样的步骤大约 20-25 次。我该如何处理 for 循环(with_items)。

我可以预先定义参数 URL1、Location1、pkg1.comamd1、$pkg1.command2,并且可以在 ansible 剧本中定义它们。Pkg1 值将从 jenkins 脚本传递

- get_url:
    url: "$URL1"
    dest: $Location1
  when: $Pkg1 != 'NONE' 
- Name : run the commands
  Shell: sh $pkg1.comamd1; sh $pkg1.command2
  when: Pkg1 != 'NONE' 

如何创建变量数组并使用_items

VarDetails {Pkg1, URL1, Location1, comamd1a, $command1b
            Pkg2, URL2, Location2, comamd2a, $command2b
            Pkg3, URL3, Location3, comamd3a, $command3b
            ....................
            ....................
            }    

标签: loopsansible

解决方案


我没有测试过,但在使用项目列表时它必须与下面的参考示例一起使用。

- name: more complex items to add several users
  user:
    name: "{{ item.name }}"
    uid: "{{ item.uid }}"
    groups: "{{ item.groups }}"
    state: present
  with_items:
     - { name: testuser1, uid: 1002, groups: "wheel, staff" }
     - { name: testuser2, uid: 1003, groups: staff }

不要忘记通过更改在变量之前添加项目

url: "$URL1"
dest: $Location1

url: "item.url"
dest: "item.location"

在 with_items 中引用时.. 使用您的变量 $URL1, $URL2


推荐阅读