Overnight improvements and an impressive final Q3 effort from Hamilton put him just 0.179s shy of Vettel's pole time meaning the reigning champion will start Sunday's race from the front-row.
Bottas took up the chase and received the lucky break he needed when the Red Bull crash caused a safety auto period, allowing him to pit more quickly and replace Vettel as leader.
Carlos Sainz rounded out the top 10 as McLaren failed to get a vehicle through to Q3.
Sebastian Vettel finally yielded his lead as he pitted on lap 31 surrendering the top spot to the Mercedes of Bottas.
Red Bull's Australian driver Daniel Ricciardo celebrates with the trophy after the Formula One Azerbaijan Grand Prix in 2017.
"The good point is that our vehicle was really good this afternoon so it should be in a good place tomorrow", added the four times world champion after his 53rd career pole.
Before the bad denouement, there was some marvellous wheel-to-wheel racing between Max Verstappen and Daniel Ricciardo, with the Australian making a pass at the first corner to take his team-mate's fourth position on Lap 34. Only 13 cars completed the race.
Broncos Enter Last Day Of NFL Draft With 4 Picks
OR running back Royce Freeman , here sprinting through a hole against Wyoming on September 16, was selected in the third round by the Broncos on Friday night.
Verstappen's vehicle was lifted briefly into the air and both battered Red Bulls skated down the escape road into retirement.
A frustrated Hamilton complained about back markers, but began clawing back time, recorded a fastest lap and then saw Bottas go eight-tenths quicker.
Raikkonen, starting sixth, attempted to pass inside Ocon's Force India, but the Frenchman turned in and as the pair collided he crashed into the wall.
The safety vehicle came out following the contact between Verstappen and Ricciardo. Alonso limped back to the pits with two punctures and managed to rejoin the race. That delayed the restart, and when it came Vettel charged down the inside of Bottas but couldn't slow enough to make the corner and went onto a runoff area. Bottas led Vettel, Hamilton, Raikkonen, Perez, Grosjean, Sainz, Leclerc, Stroll and Alonso behind the SC.
Hamilton's lack of a pace advantage on fresh, but harder, rubber allowed Vettel to stay out until lap 30 before taking on softs, but Bottas ran even longer.
Canadian Lance Stroll, third in Baku a year ago, will start 10th for Williams - the only team yet to score a point this season.
"Without the safety vehicle it would have been easier for us - there is probably 47 laps of positive and maybe one turn without a positive note".
The Aussie qualified fourth in Saturday's session, just edging out team mate Max Verstappen after progressing through the first two segments without any major drama and enjoying a "decent" last effort in Q3.