Spain were staring a shock defeat to Morocco in the face before a dramatic leveller from substitute Iago Aspas.
The Liverpool flop's clever finish, coupled with Iran's late equaliser against Portugal means Spain top the group.
The 2010 champions now face Russia in the last 16 but they will have to improve on their performance here.
Fernando Hierro's side fell behind early on against Morocco after a defensive mix-up.
Sergio Ramos and Andres Iniesta didn't communicate and Khalid Boutaib took full advantage as he slotted his finish between the legs of David De Gea.