抛出错误时如何处理ok流程

问题描述 投票:0回答:1

我发现以下方法可以通过 ansible 为 Active Directory 域创建主反向区域:

    - name: Create reverse DNS zone
      ansible.windows.win_shell: Add-DnsServerPrimaryZone -NetworkID {{ reverse_dns_zone }} -ReplicationScope Forest
      retries: 30
      delay: 60
      tags: debug
      until: result is succeeded

我知道想要创建一种更加幂等的方法。我遇到的唯一问题是,第二次运行该命令,它总是失败:

Add-DnsServerPrimaryZone : Fehler beim Erstellen der Zone "0.3.10.in-addr.arpa" auf dem Server "DC01".
In Zeile:1 Zeichen:1
+ Add-DnsServerPrimaryZone -NetworkID 10.3.0.0/20 -ReplicationScope For ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (0.3.10.in-addr.arpa:root/Microsoft/...rverPrimaryZone) [Add-DnsServerPrimaryZone], CimException
    + FullyQualifiedErrorId : WIN32 9609,Add-DnsServerPrimaryZone

看着

CategoryInfo    : ResourceExists
我认为这对于我的方法来说可能是一个很好的成功状态,但是使用

until: result.stderr.find('ResourceExists') != -1

总是导致任务失败。

这种情况下正确的做法是什么?

powershell ansible
1个回答
0
投票

您可以使用

try/catch
语句来选择性地抑制错误:

try {
  Add-DnsServerPrimaryZone -NetworkID {{ reverse_dns_zone }} -ReplicationScope Forest -ErrorAction Stop
}
catch [Microsoft.Management.Infrastructure.CimException] {
  if($_.CategoryInfo.Category -ne 'ResourceExists') {
    # re-throw unless it's a ResourceExists error
    throw 
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.