DEV Community

Discussion on: Terraform: Is it ok to "read or create" a resource?

junkern profile image
Martin • Edited

I can totally see where you are coming from. And your solution is (from a solution-oriented perspective) cool, but it is not how you should approach terraform resources.

Short version: Either create a different role for each service or you create the "dynamo DB-access" role and simply use data sources to import the role-name into your services.

(I submitted too early, longer version is in the making)
Long version: You are experiencing that error, because you are trying to create the same role in every instance of the module. So you either have to create the role at a centralized point in your terraform code and then simply pass the role-name into your module, so that the module can attach the role name to an instance (or whatever you want to do with that role).

Another alternative would be to create roles for each service ("service-a-role", "service-b-role") and then every role would have the needed policies for the service (access DynamoDB, access S3). That way the role creation can also happen within the module and you won't get resource clashes, as every role would have a unique name. To my knowledge, this is also the recommendation of AWS, because you can better manage what every service is able to access.

It really depends on your architecture, whether service-specific roles is a possible thing.

In case you haven't heard about terragrunt, I would definitely check it out! It makes working with terraform a lot easier:

gf_developer profile image
GF Author

Thanks for the detailed response!
Yes, a unique name is really good, and I thought about creating common resources apart from a service config and then use some id, like arn or name in service config, but in this case, it could be tough to detect from which modules application depends on. Also, it is difficult for me, at least right now, to accept the fact that the application config won't work until a few other configs are applied, moreover, if the order of appllying is important, it probably will worth to store that information somewhere
Thanks for terragrunt too, I'll try everything that reduces routine with terraform :)