MADRID—The North Atlantic Treaty Organization is on a course to admit Finland and Sweden following an agreement with Turkey, a move that would add vast territory and new military abilities in the wake of Russia’s invasion of Ukraine.

The two Nordic countries, which had long shunned joining the alliance, abruptly changed their stance following Moscow’s attack on its neighbor on Feb. 24.

Both countries applied for NATO membership a month ago, but Turkey had balked, taking exception to how Sweden, in particular, has handled issues of Kurdish terrorism raised by Ankara.

Polish soldiers land from a helicopter during a military exercise of NATO troops near Orzysz, Poland, in May.

Photo: KACPER PEMPEL/REUTERS

“In light of the progress we have made, [Turkey] has agreed to support Finland and Sweden” in their membership bids, said NATO Secretary-General Jens Stoltenberg in announcing the deal on Tuesday.

All other members of the 30-country alliance had endorsed the two countries bid to join NATO, so Turkish President Recep Tayyip Erdogan’s agreement with leaders of the two candidate countries appears to clear the way for the alliance’s expansion.

“I’m absolutely confident,” said Mr. Stoltenberg, about the countries’ accession. “We met, we discussed and we found a good solution,” he said, summing up the last-minute deal-making before NATO’s annual summit.

The leaders of the three countries signed a memorandum following a meeting that lasted for more than three hours in Madrid on Tuesday, in which Sweden and Finland committed to work with Turkey on issues of concern to it.

Turkey assented to the two countries’ applications after they committed in writing not to provide support to groups that Turkey considers Kurdish terrorists and condemn terrorism against Turkey, according to the text of their memorandum. They also agreed to work with Turkey on extraditions of accused terrorists, terrorist financing and similar issues.

President Biden called Mr. Erdogan Tuesday morning to talk about the Nordic countries’ bids, at the request of their leaders, according to a senior Biden administration official. The official said Mr. Stoltenberg deserved “enormous credit for what he did to get this across the line.”

Earlier, in response to the prospect of a deal, Russia threatened to station ballistic missiles and nuclear weapons on its border. Dmitry Medvedev, deputy chairman of the Russian Security Council, said Moscow didn’t see a threat from Sweden and Finland in NATO because past relations with the countries had been “quite respectful and mutually well meaning,” he told government newspaper Argumenty i Fakty. But Russia would still need to ready itself, Medvedev said.

British soldiers take part in maneuvers during an exercise in May in Voru, Estonia.

Photo: Jeff J Mitchell/Getty Images

The deal lifts a cloud that had threatened to overshadow the summit. With the two countries’ entry now looking likely, leaders can focus on issues they had planned to address.

Before Russian forces invaded Ukraine in February, NATO officials assessing the alliance’s strategic direction were weighing new threats ranging from China to hybrid warfare and climate change. Moscow’s attack refocused their attention on its original mission: the danger next door.

In the months since President Vladimir Putin ordered his armies into Ukraine, the U.S. and its NATO allies have mounted their biggest mobilization since the end of the Cold War. The alliance immediately assumed a war-ready alert level for its front-line forces and put more than 100 planes on patrol from the Black Sea to the Arctic Circle. Members deployed thousands more troops near Russia’s border and began dispatching weapons and other aid to Kyiv.

Mr. Stoltenberg on Monday said the alliance would increase to more than 300,000 from 40,000 the number of troops it keeps on high readiness, even as it keeps an eye on future threats.

South Korean President Yoon Suk-yeol and his wife, Kim Keon-hee, disembark the presidential plane upon arriving in Madrid ahead of the summit.

Photo: Yonhap News/Newscom/Zuma Press

President Biden and leaders of the alliance’s 29 other countries at the summit plan to declare Russia “the most immediate threat to our security,” Mr. Stoltenberg said recently.

To address that threat, NATO is building on years of preparation, he said.

Russia’s invasion has upended plans for the summit, a normally heavily scripted event. “There’s the list of what we had in mind before February 24 and the list post-February 24,” said U.S. Ambassador to NATO Julianne Smith.

The invasion also forced multiple rewrites of NATO’s new decade-ahead blueprint, its “Strategic Concept.” In it, they plan to scrap wording from the 2010 version calling Russia a strategic partner.

China, which wasn’t mentioned in the last strategic concept, remains a focus for the summit. In a sign of the new emphasis, NATO for the first time has invited leaders of its Asia-Pacific partners including Japan, South Korea and Australia to participate. “We want to have a conversation with them about China in particular, and China and Russia,” whose increasing alignment on many issues concerns free-market democracies, Ms. Smith said.

The summit will initiate efforts to expand the number of troops under NATO command and rethink how they are organized, part of what the alliance is calling its New Force Model. Members far from Russia are set to commit troops to defend front-line countries, as Germany recently did for Lithuania.

Leaders will also plan how to rebuild armament stockpiles depleted by shipments to Ukraine’s front lines. Members this year have pledged to boost military spending, potentially adding more than $100 billion annually to alliance-member outlays, an increase that would exceed Russia’s entire yearly defense budget.

“NATO was a social club for 30 years,” said David E. Johnson, a retired U.S. Army colonel who served in Europe and at NATO’s military headquarters during the Cold War. “Suddenly it’s a military alliance again.”

Ukrainian soldiers load Javelin antitank missiles into a military trucks at Boryspil airport, outside Kyiv.

Photo: Efrem Lukatsky/Associated Press

But while NATO has pivoted sharply in recent months, the alliance’s repositioning to defend against and deter Russia isn’t sudden. Change quietly began around 2014, after Moscow seized the Crimean Peninsula from Ukraine and fomented an uprising in the country’s east.

That year was a turning point, said Gordon “Skip” Davis, a retired U.S. Army major general who served as a NATO deputy assistant secretary-general until September and helped orchestrate a rethink of the alliance’s military strategy. “NATO realized it had to react faster, on a bigger scale,” he said.

The shift that began then, and which will be reinforced at the summit, builds on three decades of adaptation, NATO veterans said.

NATO’s decision in 1999 to build a new headquarters prompted some critics to ask why the alliance itself was necessary, much less a new building. The Soviet Union had long since collapsed, removing the purpose for NATO’s creation in 1949.

But instead of folding the alliance, members found new applications for the military integration they had spent decades achieving.

A U.S. soldier manning a machine gun on board a Chinook helicopter over Afghanistan’s Paktia province in 2014.

Photo: SHAH MARAI/Agence France-Presse/Getty Images

“You also need NATO when tensions are low,” said Mr. Stoltenberg. Alliance defensive capabilities, command structures and adaptability must be maintained for crises, he said. “You cannot just switch NATO on and off.”

After helping end fighting in former Yugoslavia in the 1990s, NATO shifted to combating terrorism after the Sept. 11, 2001, attacks on the U.S. and oversaw the U.S.-led military operation in Afghanistan that ended last year. Following Russia’s invasion of neighboring Georgia in 2008, NATO started working with Tbilisi and Kyiv to prepare for more Russian hostilities. In 2011, NATO helped enforce an arms embargo and no-fly zone in Libya.

SHARE YOUR THOUGHTS

What is NATO’s role in the current geopolitical environment? Join the conversation below.

“NATO’s been lucky because something has always come along to show why it’s needed,” said Jamie Shea, a retired top NATO official who said the post-Cold War years made the alliance more flexible.

NATO’s enduring utility, said former U.S. Ambassador to NATO Ivo Daalder, is maintaining the postwar peace among Washington’s European allies.

“Having the U.S. present physically in Europe is what makes the difference between war and no war,” he said, noting that U.S. engagement allayed French and British concerns about German reunification in 1990.

Now, similar thinking underpins NATO members’ help for Ukraine. Poland and the three small Baltic countries have delivered vast quantities of weaponry relative to their size in part because they trust that other alliance countries would protect them if needed.

Police patrol ahead of the NATO summit in Madrid.

Photo: Manu Fernandez/Associated Press

NATO’s recent jump to action appears all the more notable because just a few years ago its usefulness again faced questions. Former President Donald Trump called it obsolete. At the 2018 NATO summit in Brussels, he jolted allies with what sounded like a suggestion that he could pull the U.S. out, threatening to “do my own thing.”

The next year, French President Emmanuel Macron said NATO was experiencing “brain death.” Mr. Macron’s read on NATO was wrong, said Mr. Davis, but the two presidents’ comments were “useful impetus for the secretary-general,” who launched a big internal review at NATO’s 2019 summit.

A year later, Mr. Stoltenberg received the group of experts’ report enumerating proposals to prepare NATO for the coming decade. Many focused on political interactions, rather than military operations.

Covid-19 provided extra momentum for enacting recommendations to make NATO more nimble because the pandemic shook up procedural routines. It forced officials to work differently, often through virtual networks rather than around conference tables, Mr. Davis said.

The Biden administration’s renewed enthusiasm for NATO and trans-Atlantic ties further re-energized the alliance, officials say.

By last summer, when coronavirus restrictions began easing, NATO’s more-flexible routines had been established, said Mr. Davis. When U.S. intelligence learned last fall that Russia was preparing to invade Ukraine, NATO was able to react more quickly than it could have three years earlier, he said.

NATO’s transformation “is not something that started on the 24th of February—it has been going on for several years,” said Mr. Stoltenberg. When Russia attacked, he said, “We were well prepared.”

Write to Daniel Michaels at daniel.michaels@wsj.com and Jared Malsin at jared.malsin@wsj.com