Skip to content Skip to sidebar Skip to footer

Ansible Purchasing A Domain Name And Using Python To Parse The Xml Output

This is an action in my Ansible playbook: - name: Purchase Domain Name local_action: > uri url=https://api.sandbox.namecheap.com/xml.response method=GE

Solution 1:

lxml can easily parse this string as 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/20137:51:07AMUTC'

Solution 2:

There's a recent, external Ansible module that allows to parse and manipulate XML, check it here

Unfortunately, even if it is supposed to accept XML strings (and thus Ansible variables) as input, I couldn't get it to work properly. You would have to save your XML to a file first, and then parse it:

-name:PurchaseDomainNamelocal_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:saveNamecheapoutputcopy:content="{{domain_name_purchase.content}}"dest=resp.xmldelegate_to:localhost-name:ParseNamecheapXMLxml:file=resp.xmlxpath="/ApiResponse/etc..."content=textregister:resp_status_nodedelegate_to:localhost-debug:msg="{{resp_status_node.matches[0]}}"

Post a Comment for "Ansible Purchasing A Domain Name And Using Python To Parse The Xml Output"