Invalid character while using "terraform plan -out main.tf"

Whenever I run “terraform plan -out main.tf” command it automatically changes my main.tf file with these random characters:

PK���7 �X������������� �tfplanUT���Lflб��@��rxly�ȁ S�%�d��ٔ�����"�e�%�5� o&�u���?D�X�BJK ��ED_�-><~g�/�_��

�7J"�d����6�C"(5���W5�Z M�

���ԲW���y�f?|T���ɡ����8�uؓ68��A�2/6Ӿ��a0Ư��Tv:8բ�~��,�p��#�m�Z�m�o�e�9Zw��O��.�EY,y���~Z������X�D�GA�C�͓��]2�

�’�d���F�+�v�;��� ��I`^��M��Td��f����۳[��=}4���R�tqCb }��4

Ҁ���8�?��q�,Ze|�%�����y?����PKac��U�����PK���7 �X������������a� �tfstateUT���LfD�ͮ�0F�<E3�[�E~*�b ʌ+5S���u��;��� ��M� ���7A���KS� �@���Auy�e%�Q�x�kj�5v��g��z���yF�\Ul��~����`P���P�Q,%t�fd�d�P�.�kt�8�O�����PKapm���������PK���7 �X������������ � �tfstate-prevUT���LfD�=

B1 ���"d�����*"�R�c+I���ݥqp�~���-�b��nr’�tk�Z��y9�w%)�1�ޑK�t�9�z����ae.���d��ru������Y�9��

����PKa>��

But when I use “terraform plan” it works absolutely fine.

Hi @sehajkapoor001,

This is expected behaviour but I believe you may be misunderstanding the use of the terraform plan -out=[plan file] command.

The use of the -out option writes the generated plan to the given filename that you can later pass to terraform apply to execute the planned changes.

So the plan command reads your module, including your main.tf but in your case overwrites your main.tf as you have asked it to, whereas what you really want is for it to output to a separate file that you later pass into the apply command using the apply command’s saved plan mode
Usage: terraform apply [options] [plan file]

Where [plan file] is the file created by the above terraform plan command.

As per the documentation in the above link:

Terraform will allow any filename for the plan file, but a typical convention is to name it tfplan. Do not name the file with a suffix that Terraform recognizes as another file format; if you use a .tf suffix then Terraform will try to interpret the file as a configuration source file, which will then cause syntax errors for subsequent commands.

…and…

The generated file is not in any standard format intended for consumption by other software

Hope that helps