Search code examples
gitlabterraformgitlab-cigitlab-ci-runnerterraform-provider-aws

how to delete terraform resources in gitlab?


I create resources through gitlab, but I can't delete them. At the beginning, I output the plan to artifacts to apply it in apply. Then resources are created and after creation I want to delete them. But it does not work to delete them, it is impossible to output them to out in the same way as the plan, and if I just type destroy, as in the terminal, that the job is running successfully, but 0 resources is deleted. My.gitlab-ci.yaml is like this

stages:
  - validate
  - plan
  - apply
  - destroy

before_script:
  - rm -rf .terraform
  - export AWS_ACCESS_KEY_ID
  - export AWS_SECRET_ACCESS_KEY  
  - terraform init

validate:
  stage: validate
  script:    
    - terraform validate
  tags:
    - shell-runner

plan:
  stage: plan
  script:
    - terraform plan -out "planfile"
  dependencies:
    - validate
  artifacts:
    paths:      
      - "planfile"      
  tags:
    - shell-runner
      
apply:
  stage: apply
  script:
    - terraform apply -input=false -auto-approve   
  dependencies:
     - plan
  tags:
    - shell-runner
  when: manual

destroy:
  stage: destroy
  script:
    - terraform destroy -state="planfile" -auto-approve
  tags:
    - shell-runner
  when: manual

Solution

  • I found one of the solutions + can be done via s3 bucket https://docs.gitlab.com/ee/user/infrastructure/iac/terraform_state.html