@@ -38,17 +38,30 @@ async def resolve(self, dns: str) -> ConnectionName: # type: ignore
3838 except ValueError :
3939 # The connection name was not project:region:instance format.
4040 # Attempt to query a TXT record to get connection name.
41- try :
42- result = await super ().resolve (dns , "TXT" , raise_on_no_answer = True )
43- if result is not None :
44- rdata = result [0 ].to_text ().strip ('"' )
45- conn_name = _parse_instance_connection_name (rdata )
46- except ValueError :
47- raise DnsResolutionError (
48- f"Unable to parse TXT for `{ dns } ` -> { result [0 ]} "
49- )
50- except Exception as e :
51- raise DnsResolutionError (
52- f"Unable to resolve TXT record for `{ dns } `"
53- ) from e
41+ conn_name = await self .query_dns (dns )
5442 return conn_name
43+
44+ async def query_dns (self , dns : str ) -> ConnectionName :
45+ try :
46+ # Attempt to query the TXT records.
47+ records = await super ().resolve (dns , "TXT" , raise_on_no_answer = True )
48+ # Sort the TXT record values alphabetically, strip quotes as record
49+ # values can be returned as raw strings
50+ rdata = [record .to_text ().strip ('"' ) for record in records ]
51+ rdata .sort ()
52+ # Attempt to parse records, returning the first valid record.
53+ for record in rdata :
54+ try :
55+ conn_name = _parse_instance_connection_name (record )
56+ return conn_name
57+ except Exception :
58+ continue
59+ # If all records failed to parse, throw error
60+ raise DnsResolutionError (
61+ f"Unable to parse TXT record for `{ dns } ` -> { rdata [0 ]} "
62+ )
63+ # Don't override above DnsResolutionError
64+ except DnsResolutionError :
65+ raise
66+ except Exception as e :
67+ raise DnsResolutionError (f"Unable to resolve TXT record for `{ dns } `" ) from e
0 commit comments