How to Automate VM provisioning and setup using code?
First and foremost, there are several tools for better managing and provisioning of infrastructure such as Terraform.
You could create a pipeline to create things automatically as needed (based on triggers or manual start) on Jenkins or Gitlab, your code could be created using any language using the defined cloud provider SDK or API, or the. Terraform code as previously said. I'd use the Terraform since it's way easier to manage what is there, and sincronize the current cloud state.
Also, Ansible is great to setup machines, but Terraform can do it too.