Afghan security forces battled gunmen following a suicide attack outside the Iraqi embassy in the capital, Kabul.
A bomber blew himself up at the embassy's gate, then three other attackers entered the compound, the Afghan interior ministry said.
Two Afghan embassy employees were killed, and three people, including a police officer, were injured, a spokesperson told the BBC.
So-called Islamic State (IS) said it carried out the attack.
After a gunfight lasting several hours, Afghan authorities said the attack was over and all the assailants had been killed.
The embassy is located in the central Shar-e-Naw neighbourhood. Kabul has seen a number of deadly assaults this year blamed on either IS or the Taliban.
Correspondents say this is the first attack on the city's Iraqi embassy. It comes two weeks after the embassy held a news conference to celebrate the defeat of IS in the Iraqi city of Mosul.
Pictures on social media show black plumes of smoke rising into the sky over Kabul.
During the gunfight, Iraq's foreign ministry said its top diplomat in Kabul had been taken safely to the Egyptian embassy but, according to Iraqi media, two other Iraqi staff members were fighting off the assailants.
All staff were eventually safely evacuated, an Iraqi foreign ministry spokesperson tweeted.
According to the United Nations, Afghanistan has seen at least 1,662 civilian deaths in the first half of the year, with about 20% of those in the capital.
Last Monday a suicide car bomb killed at least 30 people in a mainly Shia district of Kabul. The Taliban said they carried out that attack.
On 31 May, a huge bombing in the centre of the city killed more than 150 people, the deadliest militant attack in the country since US-led forces ousted the Taliban from power in 2001.
The violence underlines the precarious security situation in Afghanistan as US President Donald Trump weighs up whether to increase the number of US troops aiding the military and police in the country.
IS announced the establishment of its Khorasan branch - an old name for Afghanistan and surrounding areas - in January 2015. It was the first time that IS had officially spread outside the Arab world.
In response to the embassy attack, the commander of Nato's Resolute Support mission in Afghanistan paid "respect and gratitude" to Afghan forces.
"[IS] failed in this attack and they will be defeated," Gen John Nicholson said.