powershell - 从PowerShell到Ansible的输出,以用于Ansible条件/控制播放执行

标签 powershell ansible ansible-playbook

我通过调用PowerShell脚本在Windows主机上使用Ansible。效果很好,但我的Playbook要求只根据条件播放剧本(使用Ansible时间)。

我面临的挑战是如何从PowerShell输出到Ansible。作为一个用例,假设我有两个角色。第一个播放调用脚本以检查PowerShell版本号,第二个播放仅在PowerShell版本为5.0时运行。

如果可能的话,我如何将第一部剧本的PowerShell脚本中的变量输出回Ansible,该变量可以在第二部剧本的“何时”使用,以允许或阻止执行?

最佳答案

对于这种特定情况,您可能只想使用ansible_powershell_version事实,例如:

- name: do PS5-only thing
  raw: Run-SomePS5Thing
  when: ansible_powershell_version >= 5

但是通常,要捕获var中的内容并在以后使用,您可以仅在命令任务上将register:关键字与下游任务上的过滤器结合使用,以提取所需的值,例如:
  # Filters can deal with text too, but since it's Powershell, 
  # let's use structured data- ConvertTo-Json gives us something Ansible
  # can read with the from_json filter
  - raw: Get-NetRoute 0.0.0.0/0 | ConvertTo-Json -depth 1
    register: routeout

  # use from_json to read the stdout from raw and convert to a dictionary 
  # we can pull values from
  - debug: msg="Default gateway is {{ (routeout.stdout | from_json).NextHop }}"

  # or do something conditionally:
  - debug: msg="Default gateway isn't what we expected!"
    when: (routeout.stdout | from_json).NextHop != "192.168.1.1"

关于powershell - 从PowerShell到Ansible的输出,以用于Ansible条件/控制播放执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38923475/

相关文章:

sudo - 无法让 sudo 命令与 Ansible 一起使用

ansible - 如何在ansible的主机文件中指定用户名

powershell - 在 Powershell 中使用 nslookup 获取主机名的 IP 地址

重新启动后 Ansible ssh 连接超时

ansible - 仅在定义变量时设置附加的 ansible 模块参数

loops - 如何在 Ansible 中获取子组列表?

ansible - 在嵌套的剧本之间传递变量

powershell - Azure Functions 中 PowerShell 脚本的选项在哪里

powershell - 有没有比输入 | 更快的方法来计算 powershell 中的行数?测量对象

powershell - 关于powershell命令执行的问题