Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Existing EC2 instance to CloudFormation json/yaml

Problem:

I have an EC2 instance running and I have made some modifications to the instance: installed docker, setup directories for certs, etc. Now, I am wanting to create the same instance but use infrastructure as code principals. Instead of remembering all the additions that I have done and creating a template by hand, I am trying to find a way to export my current EC2 instance into a json or yaml format so that I can terminate this instance and create another one that is equivalent to the one running.

I have tried:

aws ec2 describe-instances

Reading through the AWS CLI EC2 docs

Reading through the CloudFormation docs

Searched Google

Searched SO

like image 851
Chris Bolton Avatar asked Sep 18 '25 02:09

Chris Bolton


2 Answers

Since you have no knowledge of how the instance was setup, the only choice is to create an Amazon Machine Image (AMI). This will create an exact copy of the disk, so everything you have installed will be available to any new instances launched from the AMI. The CloudFormation template can then be configured to launch instances using this AMI.

If, on the other hand, you knew all the commands that needed to be run to configure the instance, then you could provide a User Data script that would run when new instances first boot. This would configure the instances automatically and is the recommended way to configure instances because it is easy to modify and allows instances to launch with the latest version of the Operating System.

Such a script can be provided as part of a CloudFormation template.

See: Running commands on your Linux instance at launch - Amazon EC2

like image 170
John Rotenstein Avatar answered Sep 19 '25 19:09

John Rotenstein


One option would be to create AMI from live instance and spin up new CF stack using the AMI.

Other would be importing resource: https://aws.amazon.com/blogs/aws/new-import-existing-resources-into-a-cloudformation-stack/

like image 21
Oleksii Donoha Avatar answered Sep 19 '25 18:09

Oleksii Donoha