This is really a good question that I've been thinking of. I'd like to add something here.
A simple answer to the question, and to the point that scrum means everything should be done is done in the end of the sprint, is automation should be done together along with other tasks in the sprint.
But that is too realistic. In the real world, id all depends. There would be a couple of factors come to play, such as test/automation resource availability and automation ROI.
If you have dedicated testers in the scrum team, or if not everyone can write test automation, that means automation sometimes became a critical path in the sprint. If team depends on the automation being written to do regression for the current sprint, it would require good flexibility on allocating dev resources to automation development. This is something not every scrum team could do in real world. It may end up that some automation work is put into backlog and became tech-debt, which has to be handled in later sprints.
On the other hand, if a new product or new features in product is not in a stable state. Significant changes would be introduced multiple times, it is not wise to automation such areas immediately. Manual test or exploratory test would be more efficient to get the product shipped. And automate later could save a lot of automation maintenance effort. If team knows for sure this is going happen, automation early may not be a good idea. This is the nature of automation development.