The חובות הלבבות (in the beginning of the פתיחה to שער עבודת אלקים) writes, that one does not need to show gratitude to someone who did him a favor, if the favor was not intended.
ואם תגיע לנו שום טובה על ידי מי שלא כיון בה אלינו, יסתלקו מעלינו חיובי ההודאה לו ואין אנו חייבין בה
"should we obtain any benefit through one who had no such intention, the duties of gratitude to that person would cease, and we are under no such obligation."
How would the חובות הלבבות explain the well known מדרש (Quoted in רש"י שמות ח/יב and ז/יט) that Moshe could not hit the water or the earth by the first three plagues, as an expression of gratitude that they saved him when he was born, and when he killed the מצרי.
Why was it necessary to show gratitude to the water and the earth if they had no intention to save Moshe?