Last year's race winner Verstappen, 21, had dominated all three practice sessions and was on provisional pole before the final flying laps at the high-altitude Hermanos Rodriguez circuit.
If second place on the starting grid left the Dutch youngster feeling sore, the front row lockout was still Red Bull's first since the U.S. Grand Prix of 2013.
Mercedes' championship leader Lewis Hamilton, who need only finish seventh on Sunday to secure his fifth title, will line up in third place with Ferrari rival Sebastian Vettel qualifying fourth.
Formula 1
Hamilton wants new Mercedes contract before summer break
Vettel, 70 points behind Hamilton with two races remaining after Mexico, must win the race to have any chance of denying Hamilton.
"I knew it was there somewhere. We hadn't had the cleanest run through practice and I just knew putting the lap together would be crucial as always," said Ricciardo, who whooped in delight as he realised what he had done.
"I knew the pace was in the car, Max showed that all weekend from start to finish.
"I still wasn't convinced, it wasn't the cleanest (lap), but once I heard I got pole I got to relax a little," added the Australian, who is leaving Red Bull for Renault at the end of the year.
The pole was only the third of Ricciardo's career and both of those previous ones came in the tight and twisty confines of Monaco.
Verstappen lost out by 0.026, with Ricciardo setting a track record time of one minute 14.759 seconds, and he did not try and hide his disappointment.
"The whole qualifying was crap," the youngster told the global television audience. "We tried to make the best of it, I thought we had enough but it's still good to be second."
Behind the Red Bulls all eyes will be on the title contenders, with Hamilton in the stronger position after a difficult few days for Mercedes.
"I was not expecting to be up as high as we have done," said the Briton. "The team did a great job yesterday, this was as good as I could get.
"You saw what happened last year with the red car (Ferrari) behind, so it depends how we get away. We will get a good tow from the two in front so hopefully I can gain a position."
Hamilton won his fourth title in Mexico last year after starting third and then having to fight back from last to ninth following an opening lap collision with Vettel, who had been on pole but lost out to Verstappen.
Spanish Grand Prix
Hamilton overtakes Verstappen to win Spanish GP
Spanish Grand Prix
Lewis Hamilton wins Formula 1 Spanish GP - As it happened