Header Ads

Header ADS

Run Terraform only for a specific resource

The question is: 

It takes a long time to run terraform and wait. So I would like to run it to exclude rds that take the longest time to execute or I would like to run only the ec2 resource. Is there a way to do such things in terraform?


Yes, this is possible, this is not a good practice for a production environment, but for testing, there is no problem. For detailed information, you can go into the official documentation. On this page you can see the official lab for test provided by Hashcorp. 

Important to know: 

When you apply changes to your Terraform projects, Terraform generates a plan that includes all of the differences between your configuration and the resources currently managed by your project, if any. When you apply the plan, Terraform will add and remove resources as proposed by the plan.

In a typical Terraform workflow, you apply the entire plan at once. Occasionally you may want to only apply part of a plan, such as situations where Terraform's state has become out of sync with your resources due to a network failure, a problem with the upstream cloud platform, or a bug in Terraform or its providers. To support this, Terraform allows you to target specific resources when you plan, apply, or destroy your infrastructure. Targeting individual resources can be useful for troubleshooting errors, but should not be part of your normal workflow.


Let's do our main tests. 

We can use Terraform's -target option to target specific resources, modules, or collections of resources.


To call only a specific resource inside a module we can use the following: 

terraform plan -target=module.mymodule.aws_instance.myinstance
terraform apply -target=module.mymodule.aws_instance.myinstance


To call more than one module:

terraform plan -target=module.aws-docker -target=aws_key_pair.ansible
terraform apply -target=module.aws-docker -target=aws_key_pair.ansible


To call one resource when we are not using a module: 

terraform plan -target=aws_instance.myinstance
terraform apply -target=aws_instance.myinstance


You will see the following warning, which we can skip, accept and the infra will be created.

Plan: 8 to add, 0 to change, 0 to destroy.
│ Warning: Resource targeting is in effect
│ You are creating a plan with the -target option, which means that the result of this plan may not represent all of the changes requested by the
│ current configuration.
│ The -target option is not for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when
│ Terraform specifically suggests to use it as part of an error message.

Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.

Enter a value:



Further reading

    No comments

    Theme images by sandsun. Powered by Blogger.