As you may be aware, the AWS CloudFormation service is used to automate the provisioning of your infrastructure using code. However, this is accomplished by providing a template that specifies all of the services and resources necessary for infrastructure configuration. It's just adding a list of needed services, together with their names and specs, to a document that will build up your complete infrastructure all at once. The benefit is that if this infrastructure document can be standardised, it can be utilised for various clients' infrastructure configuration.
But there was something which was not possible earlier, it was the ability to utilise the existing resources which were created by either CLI or by Console.
Why do we need such feature?
Using CloudFormation you could only create new resources, but a lot of times there are some resources which you cannot afford to replace with a new one, in that case we have to use the existing resource, and thankfully AWS added support for Importing Resources using CloudFormation in Nov, 2019, in this blog I will demonstrate how can we do it.
There are a few things for which we need to be careful before trying to import our important resources.
- While importing resources make sure that the same resource is not a part of another stack
- Make sure you have permissions required to import the target resource
- Most important of all, Make sure that the DeletionPolicy is mentioned, so that if in future you don't want that specific resource in your stack, you can easily delete it without worry of loosing/deleting the resource completely.
After all of the above is checked, let's get to importing the resource.
Importing Resources in a Stack.
To import a resource we need an existing one, which I don't have, so let's try with a simple EC2 instance.
For demo, I created a t2.micro instance with default settings.
Step1: Create a template for resource with the required parameters, I have created a template for EC2 instance with the same InstanceType and AMI Id as my Instance, as you can see, I have also added DeletionPolicy as Retain.
AWSTemplateFormatVersion: 2010-09-09 Description: Import Ec2 Resources: EC2Instance: Type: 'AWS::EC2::Instance' DeletionPolicy: Retain Properties: InstanceType: t2.micro KeyName: test.pem ImageId: ami-0218d08a1f9dac831
Step2: In CloudFormation console select "Create Stack with existing resources"
Step3: In Identify resources step provide your resource details like instance Id.
Step4: Review the imported resources on the Import overview screen, if everything looks fine, just click on Import Resources, wait for it to finish importing, once it done, you can review your resources under "Resource" as shown below.
Possible Operations of Import Resource
- Can import existing resources to a new stack.
- You can import resources in an existing stack.
- You can also migrate resources to another stack.
- Detach a child stack from one parent and attach it to another to manage nested stacks.