We modelled recent observations of UV absorption of HD and \mathrm { { H } _ { 2 } } in the Milky Way and toward damped/sub-damped Lyman alpha systems at z=0.18 and z > 1.7 . N ( HD ) /N ( \mathrm { { H } _ { 2 } } ) ratios reflect the separate self-shieldings of HD and \mathrm { { H } _ { 2 } } and the coupling introduced by deuteration chemistry . Locally , observations are explained by diffuse molecular gas with 16 ~ { } { cm } ^ { -3 } \lesssim n ( H ) \lesssim 128 ~ { } { cm } ^ { -3 } if the cosmic-ray ionization rate per H-nucleus \zeta _ { H } = 2 \times 10 ^ { -16 } \mbox { ~ { } s$ { } ^ { -1 } $ } as inferred from H _ { 3 } ^ { + } and OH ^ { + } . The dominant influence on N ( HD ) /N ( \mathrm { { H } _ { 2 } } ) is the cosmic-ray ionization rate with a much weaker downward dependence on n ( H ) at Solar metallicity , but dust-extinction can drive N ( HD ) higher as with N ( \mathrm { { H } _ { 2 } } ) . At z > 1.7 , N ( HD ) is comparable to the Galaxy but with 10x smaller N ( \mathrm { { H } _ { 2 } } ) and somewhat smaller N ( \mathrm { { H } _ { 2 } } ) /N ( H I ) . Comparison of our Galaxy and the Magellanic Clouds shows that smaller \mathrm { { H } _ { 2 } } /H is expected at sub-Solar metallicity and we show by modelling that HD/ \mathrm { { H } _ { 2 } } increases with density at low metallicity , opposite to the Milky Way . Observations of HD would be explained with higher n ( H ) at low metallicity but high-z systems have high HD/ \mathrm { { H } _ { 2 } } at metallicity 0.04 \lesssim Z \lesssim 2 Solar . In parallel we trace dust-extinction and self-shielding effects . The abrupt \mathrm { { H } _ { 2 } } transition to \mathrm { { H } _ { 2 } } /H \approx 1-10 % occurs mostly from self-shielding although it is assisted by extinction for n ( H ) \lesssim 16 ~ { } { cm } ^ { -3 } . Interior \mathrm { { H } _ { 2 } } fractions are substantially increased by dust extinction below \lesssim 32 ~ { } { cm } ^ { -3 } . At smaller n ( H ) , \zeta _ { H } , small increases in \mathrm { { H } _ { 2 } } triggered by dust extinction can trigger abrupt increases in N ( HD ) .