A draw against Morocco will be enough to take them into the last 16, while Iran - who performed brilliantly - must now beat Portugal to progress.
Eight minutes into the second half, Spain broke the deadlock as a clearance by Iranian defender Ramin Rezaeian ricocheted off Costa and sailed into the back of the net, 0-1.
Spain were camped in the Iran half for the most part of the opening 30 minutes, but they struggled to find openings in the final third.
70th minute, CORNER AND FLICK: Straight from the training ground, a lovely routine sees Isco roll the ball to Silva who had peeled off his man and then popped off the ball back to Sergio Ramos inside the penalty area.
With three points from two matches, Iran still have a chance of qualifying if they can get a result against Cristiano Ronaldo's Portugal on Monday.
But the Persians kept their shape superbly, restricting Spain to a handful of chances from David Silva in the first half.
Costa scored in the 54th minute after being set up by Andres Iniesta.
- Iran are winless against European opposition at the World Cup, having lost five of their six previous fixtures (D1).
It appeared that Beiranvand exaggerated his pain after Costa stood on his foot. We all know it's tough to play them. Labelled the "Iranian Messi" Azmoun will be facing Spain in the familiar surroundings of the Kazan Arena. After two defeats, Morocco are out.
It was far from a attractive win, but the goal was enough to make Spain coach Fernando Hierro smile. The Iranians are trying their level best to get the ball in their possession, trying to score a goal.
While only one of them was a clear-cut opportunity Silva dropped deeper after the break and looked to gather the ball further away from goal. The Man City star is likely to start again against Iran and his influence will be crucial if Spain is to pick up their first victory of the 2018 World Cup.
One of those goals came from a goalkeeping howler from David de Gea, which have also turned the spotlight on the goalkeeper's form going into the second game at Kazan.