首页 > 解决方案 > 在ansible中运行一个循环来循环遍历脚本

问题描述

我有一个通过 ansible tower 运行的现有 ansible playbook。

设置如下。

包装剧本

#wrapper.yml

---
  - name: Wrapper PowerShell PB
    hosts: [x,y,z]
    tasks:

    - include_role:
        name: "{{ executeAction }}"
      register: "{{ executeAction }}_log"

    - debug: msg="{{ executeAction }}_log"

定义了另一个名为 runScript 的 ansible 角色。runScript 也是一个包装剧本,它复制作为参数传递的脚本文件,将其复制到 ansible 工作区,然后调用 powershell.exe -file 'theScriptFile.ps1'

它使用以下语法运行单个脚本,其中 ScriptFile.ps1 是传递的脚本文件参数。

---
  executeAction: 'runScript'
  script: 'myscript.ps1'

#within ansible tower,目标是能够运行多个脚本。根据我的研究,这是我想出的,这是错误的,我在这里寻找一些关于正确方法的指导。

---
executeAction: 'runScript'
loop:
  - 'script1.ps1'
  - 'script2.ps1'
loop_control:
loop_var: ExecuteThisFile
script: '{{ ExecuteThisFile }}'

在此示例中,我从 Tower 收到一个错误,即未定义变量 ExecuteThisFile。

然而,这有效。

---
executeAction: 'runScript'
script: 'script1.ps1'

约束是,它只运行一个脚本。通过将其包装成一个循环。可以执行多个脚本。

阅读了这里的文档https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html

看起来好像需要一个内部和外部循环。

对我来说,它看起来像这样。为了便于阅读,我将它们放在一行中。当我从 Tower 尝试过这个逻辑时,它会出现语法错误。

executeAction: runScript' script 'script1.ps1'
executeAction: runScript' script 'script2.ps1'
executeAction: runScript' script 'script3.ps1'

标签: ansibleansible-tower

解决方案


我最终做的是创建多个角色,每个角色都会引用一两个脚本。这消除了循环的需要。

在 ansible tower 中,我创建了一个调用角色的包装剧本。


推荐阅读