I am an expat living in Madrid, My legal residence is in Spain can I renew my NYS drivers license or do I have to be a legal residence of NY to renew my drivers license?
New York has a web page about renewing. If you look at the mail-in form on that page, it asks where you get your mail and, if different, where you live. Near the bottom of the web page it states
You can renew online if you are away and
have a valid NY driver license have had an eye exam from the last 12 months saved to the DMV Vision Registry.
However, your license will not be forwarded to you out of state or out of the country.
So, you will need to be able to truthfully state that you don't live permanently in Spain, you're merely "away". You will need address(s) to give as your New York mailing and residence addresses. You will have to arrange to get the license from the mailing address you list on the application to wherever you are when the license arrives in the mail.
I don't know if a Spanish physician would be accepted as a person to administer the vision test.
If you want a Real ID or enhanced driver license you will have to visit a NY DMV office. But if you have an unexpired US passport, the Real ID or enhanced driver license really don't give any additional benefit.
There are questions about your voter registration on the license application. Keep in mind that the criteria for being a resident for driving purposes is different than for voting. If you moved permanently to Spain, you aren't a NY resident for driving purposes, but you're still a resident of the last village, town, or city in NY you lived in for voting purposes unless/until you move back to the US.
Also bear in mind NY has an income tax. By claiming NY residency for driving purposes, you might have to pay NY income tax; check with a CPA.