简体   繁体   English

我可以在 PowerShell 脚本中运行任务吗?

[英]Can I run a task within a PowerShell script?

I am brand new to Ansible Playbooks and I have checked a bunch of different documentation without success.我是 Ansible 剧本的新手,我检查了一堆不同的文档但没有成功。 So here is what I want to do.所以这就是我想做的。 My company wants me to check to see if certain fields are present using PowerShell within winRM listeners and if they aren't they want me to make them present and if they are there they want me to skip that portion of the playbook.我的公司希望我使用 PowerShell 在 winRM 侦听器中检查某些字段是否存在,如果不存在,他们希望我让它们存在,如果存在,他们希望我跳过剧本的那部分。

- name:  Windows test
  hosts: all
  gather_facts: true
  tasks:
    - name: Run basic PowerShell script
      ansible.windows.win_powershell:
        script: |
          $winRM = Get-WSManInstance -ResourceURI winrm/config/listener -SelectorSet @{Address="*";Transport="https"}
          $winRMPort = $winRM.Port
          $winRMTransport = $winRM.Transport
          $winRMThumbprint = $winRM.CertificateThumbprint
          if($winRMPort -ne $null){
            #task goes in here
          }
          else{
            #task goes in here
          }

My question is can I put a task within the if statement to tell Ansible to run that task if it is there and don't if it isn't?我的问题是我可以在 if 语句中放置一个任务来告诉 Ansible 运行该任务吗? If now I am not sure how I would go about doing this.如果现在我不确定我会怎么做 go 。 My code below doesn't have the entire logic for the if statement just yet but I am just trying to test before I go further with it.我下面的代码还没有 if 语句的完整逻辑,但我只是想在 go 进一步使用它之前进行测试。 I have tried embedding it and it comes back with an error so I am thinking that I either am not doing it right or it can't be done at all.我已经尝试嵌入它,但返回时出现错误,所以我认为我要么没有做对,要么根本无法完成。 Any help is appreciated.任何帮助表示赞赏。 Thank you.谢谢你。

You cannot run/execute ansible task/module within powershell script.您不能在 powershell 脚本中运行/执行 ansible 任务/模块。 But you can convert the task into powershell commands/script and run it within powershell script instead of ansible task/module.但是您可以将任务转换为 powershell 命令/脚本并在 powershell 脚本而不是 ansible 任务/模块中运行它。

Since you are using win_shell, it is all PowerShell from it and not much Ansible. You could use the PS1 logic to check for condition on the WinRM port and then execute the condition.由于您使用的是 win_shell,因此它全部是 PowerShell 而不是 Ansible。您可以使用 PS1 逻辑检查 WinRM 端口上的条件,然后执行该条件。

Moreover, Ansible is idempotent so if the state is present it would by default skip the code where the condition is for "present".此外,Ansible 是幂等的,因此如果 state 存在,它将默认跳过条件为“存在”的代码。

Refer https://docs.ansible.com/ansible/latest/collections/ansible/windows/win_powershell_module.html for more details.有关详细信息,请参阅https://docs.ansible.com/ansible/latest/collections/ansible/windows/win_powershell_module.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM