Context is key in your question. What country and what position are you hiring for?
Even in places with very strong anti-discrimination laws for hiring there is always some latitude where you can discriminate against what is traditionally protected classes of people. This generally comes down to if those things are material requirements to perform the job.
Some examples that I can think of would be countries where brothels are legal. You may need to hire women therefore you would advertise that's the gender you need. Another example would be some sort of acting gig. The roles that need filled can be determined by a script and the script & plot dictates that do you need very specific genders and races for this.
As an open-ended question without any context it sounds like a very bad question to be asking. Usually this is the type of question that if you have to ask is this okay generally means that it is not okay for you to do this. The limited situations where it is okay to make this kind of discrimination are generally obvious.
Your question is "Is it ok?" rather than "Is it legal?".
Assuming you have checked the legality of this hiring criteria in your country/state...
I think it is ok, I live in a country with very little regulation, by choice mainly.
I think it is ok because your job ad will be up front and honest. If you provide context (e.g. you are hiring for sensitive counseling position dealing with specific issues), you can speed up the hiring process.
If you provide no context, a good assumption is that your company has some sort of bias, and potential applicants can speed up their job search by skipping yours. It's a time waster to find out about that bias during the interview process, or worse, during your employment.
I would prefer that people do it, assuming they are set on using race and gender as a hiring requirement. Saves the time of those who do not fit the desired categories.
In almost all cases, it's not okay to even have only certain races or genders you're willing to hire. If you have a BFOQ exception that makes that okay, then it would be okay to announce it too.
That's what the US Code itself says, but I thought there was a court ruling somewhere that the First Amendment overrode this in the specific case of casting actors for a creative work.
To test, just take the wording you're thinking about using, and substitute in "white male" or whatever, as needed. For example, "only white males need apply." Or if your statement is negative, try something like "no Jews, please." See how it sounds.
[1]https://www.shrm.org/hr-today/public-policy/hr-public-policy....