The Manu, who entered the tournament as top seeds, trailed 12-0 midway through the first half but hit back in the with tries to Alex Samoa and Alex Fidow to lead 14-12 at halftime.
Samoa stretched their lead to seven points when Belgium Tuatagaloa crossed early in the second half.
Spain closed the gap to 19-17 with three minutes to go to ensure a tight finish and clinched their Olympic berth in the dramatic fashion, with Ignacio Martin crossing the line as time expired to break Samoan hearts.
An emotional Spain captain Pablo Feijoo was overwhelmed at their achievement.
“It’s so crazy. I can’t believe it. It’s a dream for us – we’ve been working, some of us, fifteen years for this.”
Samoa had earlier beaten Hong Kong 31-12 in the quarter finals and Germany 24-14 in the semis to progress to the final.
Tonga finished tenth at the repechage event after losing to Zimbabwe 31-5 in the Challenge Trophy final.
Tonga failed to win any of their pool games against Samoa, Zimbabwe and Ireland but thrashed South Korea 41-7 and Uruguay 35-12 in the Challenge Trophy quarter and semi finals.
- RNZI