Canadian youngster Lance Stroll, in eighth, out-qualified his fellow Williams driver Felipe Massa, who was ninth.
Current world championship leader Sebastian Vettel will start from the second row of the grid after only qualifying fourth.
The Azerbaijan Grand Prix takes place Sunday at 9AM ET from Baku City Circuit.
It was surely disappointing to lose second place for Stroll, but Williams can't be that sad about achieving the team's first podium this season.
Bottas seemed on course for just his second career pole before Ricciardo's error caused a break.
"And then Lewis, what he did today, no one else I think can do that".
He outpaced team-mate Valtteri Botass by half a second and was more than a second clear of third-placed Raikkonen with Vettel 1.25 seconds adrift in fourth.
Gesturing wildly, Vettel then pulled alongside Hamilton's auto and appeared to turn into the side of the Mercedes, with the pair banging wheels before the race then resumed.
The safety auto came out three times in quick succession before a red flag stopped the race on lap 22 of 51 because debris littered the track.
With a long run up between the following Turn 16 and the safety vehicle line, Hamilton had to back off to ensure that he did not break the rules by overtaking the safety auto before he was allowed.
The incident was investigated by the race stewards, after a chaotic red flag stoppage, and Vettel was handed a 10-second stop and go penalty. Both Vettel and Hamilton were left in deep conversation with their teams regarding their clash, with the stewards doing much the same, confirming the incident was under investigation.
Hamilton has slipped to 14 points behind Vettel in the F1 world drivers' championship after the opening eight rounds of the 2017 F1 season. Vettel and Hamilton were also able to slip past Magnussen before coming across Ocon, the Force India being made light work of, making Bottas the next target with six laps to go, who himself was catching Stroll at a rapid rate of knots.
The fact Ricciardo won from 10th on the grid, and that Bottas clawed his way back from last following an early incident, summed up a freakish race. "I really enjoyed it". I am just happy with myself. I can't describe how I feel, it is beyond wonderful. In the race, with more laps, the tyres should start working better.
But he came through at the last minute, beating Mercedes team-mate Valtteri Bottas' time by nearly half a second and clinching the 66th pole of his career. It was all or nothing, but the lap just got better and better throughout. Today where we did well was to stay out of trouble, let some other drivers make mistakes and get to the end. Vettel threw his hands in the air, pulled his Ferrari alongside and barged the wheels of Hamilton's Mercedes. Valtteri Bottas drove his Mercedes to second place right at the last possible moment heading into the chequered flag, ahead of Lance Stroll's Williams auto and behind the race victor, Red Bull's Daniel Ricciardo.