Captain Greig Laidlaw scored the decisive try in the final seven minutes, though the Scots had to cling on following Motu Matu'u's late score.
Samoa scored through Tusi Pisi, Ma'atulimanu Leiataua and Rey Lee-Lo in a thrilling first half.
Tommy Seymour and John Hardie crossed for the Scots before the break.
Scotland also had Ryan Wilson sin-binned in the first half for stamping.
The Wallabies beat the Welsh 15-6 at Twickenham and will now face Vern Cotter's Pool B runners-up, with South Africa having already won the section.
Same old Scotland