Did the Germans have to take Gibraltar to block [the] entrance into the Western Med?
No they didn't. Taking Gibraltar is the most effective way to do it, but all they have to do is render it hors de combat and they can do that by making the airfield and naval base unusable.
hors de combat
adjective out of action due to injury or damage.
Looking at a map, I wonder if the Germans in WW2 could have just established a base at Tarifa and then destroyed the Gibraltar air field with artillery and bombing and used the Tarifa air and artillery base to effectively seal off the Western Med.
Yes they could.
Of course, this assumes an alliance with Spain (a big assumption) but it would obviate the expensive assault on the Rock.
Franco giving in to
the great temptation in June 1940 is a prerequisite. However, there are the oft quoted problems of the material condition of Spain in the summer of 1940, fuel supply and food supply. And there are the oft quoted problems of the material condition of Spain in the summer of 1940, fuel supply and food supply. Finally for the people that haven't read the last two sentences I acknowledge that it would be difficult for Franco to do that because of the oft quoted problems of the material condition of Spain in the summer of 1940, fuel supply and food supply.
Having acknowledged that the material condition of Spain in the summer of 1940, fuel supply and food supply makes Franco joining the Axis in June 1940 unlikely, making Gibraltar unusable is one of the few things that the Spanish armed forces were capable of.
AIUI they had enough artillery and ammunition for a prolonged bombardment of the naval base and airfield.
Much is made of the coast artillery that the British had at Gibraltar (which included seven 9.2" guns) which would make the strait impassable to Axis shipping, which is perfectly true.
However, one of the things that the Spanish did have an abundance of was cost artillery. Unfortunately, I don't have the exact figures, but the Spanish guns in the Strait of Gibraltar in the summer of 1940 did include some 12" and 11" guns which would make the strait impassable to British shipping.