首页 > 解决方案 > Ansible - 循环变量

问题描述

我正在尝试使用 ansible 剧本启动应用程序。

变量 inst 获得了所有必需的软件 ID:

WEB
TS3
SQL
....

如何为所有软件 ID 创建一个循环并在所有软件上运行相同的命令?

---
- name: "start sw"
  become: yes
  command: "swstart {{ inst }}"
  retries: 3
  failed_when: ( instance_start.rc not in [ 0 ] )

标签: ansibleyaml

解决方案


您应该首先将您的列表定义为 playbook 上的变量。之后你可以使用

with_items

像那样:

---

- hosts: all
  remote_user: root
  vars:
    softwares:
    - WEB
    - TS3
    - SQL
  vars_files:
    - /softwares.yml # if you need to import data from file

  tasks:

  - name: display your softwares using debug module
    debug:
      msg: "An item: {{ item }}"
    with_items: "{{ softwares }}"

我希望这可以帮助您解决问题。


推荐阅读