I have written the terraform module with EC2 instance creation and for EC2 login I have added an instance profile with SSM IAM role creation and policy attachment in the same file.
while re-deploying the code in another region using the modules including the EC2 module I’m facing the below error.
ERROR: dev-ssm-role already exist
Is there any way it can validate that if it already exists to skip the creation from scratch and just attach the instance profile to EC2 and execute the remaining code?
Terraform just isn’t designed to do this. It is intended that a Terraform configuration specifies what resources it owns, so there is no “create if not exists” operation.
The way Terraform intends for you to handle this circumstance, is to have the configuration author specify whether to create a resource (using a resource block) or look up an existing resource (using a data block).
If you have re-useable code which needs to handle both cases, you can use the pattern of:
Thanks for this recommendation. This will work for my issue? I’m having a error message that says the resource already exists and I need to avoid this message. In my case it’s a VPC in a sandbox project, I re-use the main.tf and the VPC is created only one time.
I don’t understand well when you use the foo_bar and the condition after the equal. Can you explain more in details this?
This is an old topic, so I suggest starting a new topic where you explain your problem in detail without relying on the context from this one. The more information you share the more likely someone will be able to offer an actionable suggestion.