How to Automate VM provisioning and setup using code? Here is what I want to achieve.
I write code(Java, NodeJs, Go) to tell the program

which Cloud Provider to choose- AWS/Azure
write code to create a instance , lets say AWS - EC2 instance under which region, security pair, ports, volumes.
Then once the VM is created , write code to ssh into the system , do yum update , install docker, do other stuff and fetch certain containers. Basically ready the system for future use but mostly I would want to deploy Docker containers on these VMs later.

My question is - to achieve the above scenario which tools should be used . I understand for provisioning of the VMs in AWS , I can use the SDK, so applies for other vendors as well , but for the setup part what would be the preferred mechanism ?
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.