Ansible购买域名并使用python解析xml输出

2024-05-16 21:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的Ansible剧本中的一个动作:

- name: Purchase Domain Name
  local_action: >
        uri
        url=https://api.sandbox.namecheap.com/xml.response
        method=GET
        body="{{ namecheap_purchase_domain_name }}"
        status_code=200
        HEADER_Content-Type="application/x-www-form-urlencoded"
        return_content=yes
  register: domain_name_purchase

- debug: var=domain_name_purchase.content

它返回如下内容:

^{pr2}$

是否可以使用xmltodict.parse之类的东西来解析xml并将其转换为dict?特别是我希望返回ApiResponse Status(返回错误或成功)和Error Number。谢谢。在


Tags: namedomainlocalactionxmluriansiblecontent
2条回答

lxml可以轻松地将此字符串解析为XML:

>>> import lxml.objectify
>>> my_xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<ApiResponse Status=\"ERROR\" xmlns=\"http://api.namecheap.com/xml.response\">\r\n  <Errors>\r\n    <Error Number=\"4014104\">Possible duplicate create command for unavailable domain. Try again after 11/20/2013 7:51:07 AM UTC</Error>\r\n  </Errors>\r\n  <Warnings />\r\n  <RequestedCommand>namecheap.domains.create</RequestedCommand>\r\n  <CommandResponse Type=\"namecheap.domains.create\">\r\n    <DomainCreateResult Domain=\"elitereceipt202321414.com\" ChargedAmount=\"0\" DomainID=\"0\" OrderID=\"0\" TransactionID=\"0\" WhoisguardEnable=\"false\" FreePositiveSSL=\"false\" NonRealTimeDomain=\"false\" />\r\n  </CommandResponse>\r\n  <Server>WEB1-SANDBOX1</Server>\r\n  <GMTTimeDifference> 5:00</GMTTimeDifference>\r\n  <ExecutionTime>0.07</ExecutionTime>\r\n</ApiResponse>"
>>> root = lxml.objectify.fromstring(my_xml)
>>> root.get('Status')  # Attributes use get syntax
'ERROR'
>>> root.Errors
<Element {http://api.namecheap.com/xml.response}Errors at 0x1019cd3c0>
>>> root.Errors.Error
'Possible duplicate create command for unavailable domain. Try again after 11/20/2013 7:51:07 AM UTC'

最近有一个外部的Ansible模块允许解析和操作XML,检查它here

不幸的是,即使它应该接受XML字符串(以及由此而来的Ansible变量)作为输入,我也不能使它正常工作。您必须先将XML保存到文件中,然后再对其进行解析:

- name: Purchase Domain Name
  local_action: >
        uri
        url=https://api.sandbox.namecheap.com/xml.response
        method=GET
        body="{{ namecheap_purchase_domain_name }}"
        status_code=200
        HEADER_Content-Type="application/x-www-form-urlencoded"
        return_content=yes
  register: domain_name_purchase

- name: save Namecheap output
  copy: content="{{domain_name_purchase.content}}" dest=resp.xml
  delegate_to: localhost

- name: Parse Namecheap XML
  xml: file=resp.xml xpath="/ApiResponse/etc..." content=text
  register: resp_status_node
  delegate_to: localhost

- debug: msg="{{resp_status_node.matches[0]}}"

相关问题 更多 >