The entrance gates of houses, courtyards, cities and countries [which are surrounded by mountains, or fences or walls, and thus the only exit from the country is through the entrance gate] are all obligated to have a Mezuzah placed on their door posts, if there are no non-Jewish inhabitants living in the area, as will be explained. If there are non-Jews that live within the gated area [even if they are only a minority of the population] then the entrance is exempt from needing a Mezuzah. [However some Poskim rule one is to place the Mezuzah on the entrance even if gentiles live in the area, so long as there is no worry of danger or belittlement of the Mezuzah by the gentiles.]
Must the courtyard have an opening to a home to be obligated in a Mezuzah?
According to some Poskim the entrance to a courtyard is only obligated to have a Mezuzah if the courtyard has an opening to a house that is obligated to have a Mezuzah. However if there is no such opening from the courtyard, then it does not require a Mezuzah. Other Poskim however rule that the entrance of a courtyard is obligated to have a Mezuzah irrelevant of whether it contains an entrance to a home. Practically, in such a case that there is no opening from the courtyard to a house, the Mezuzah is to be placed without a blessing.
 Shach 286/1
 Michaber ibid
 Rama ibid
 Shach 286/7
 The reason: As 1) This may enter the Jews into danger, being that the Non-Jewish governors may suspect them for witchcraft. [Shach 286/7 and Taz 286/3] and 2) The non-Jews may very likely remove the Mezuzahs and treat them with disrespect. [Shach 286/7; Perhaps the Taz omitted this reasoning as one can place the Mezuzah within the doorpost in a way that it is hidden, as he says latter on in Taz 286/4]
The ruling today: Today that the Jews are on better terms with the Non-Jewish inhabitants, and that there no longer exists belief in witchcraft, would the city gates be obligated to have a Mezuzah even if there are non-Jews living there? What about Jewish areas which have just a few powerless non-Jews living there? Is the exemption of Mezuzah only because of the suspicion for danger, or is it similar to the exemption by a house partially owned by a Non-Jew, which is exempt as is learnt from the verses, as will be explained later on? It is implied from the Shach/Taz ibid that by cities there really is no exemption and it is only because of danger that it is not accustomed to place Mezuzahs there. [So also learns Pischeiy Shearim in next footnote] However what needs to be understood is why this is any different than a home owned by a Non-Jewish partner? [See Aruch Hashulchan 286/2]
 See Pischeiy Shearim 286/3 [p. 34] and previous footnote
 Pischeiy Shearim p. 119
 Rambam; Beis Meir 299
 Rosh Mezuzah 11; Maharil 99; Tosafos Menachos 33a
 Pischeiy Shearim ibid