hashicorp / terraform-github-actions

Terraform GitHub Actions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support creation of workspace on the fly

igordcsouza opened this issue · comments

Today I'm deploying containers on ECS Fargate and start to work on deploy review apps.
So when someone opens a PR we want do raise a whole new environment, so the client/PO/whatever can use the feature and see for yourself if it's good to go for production.

Each of our environments (staging, sandbox, and production) are a new workspace and to deploy a new review app we just need to the following:

terraform workspace new feature-name
terraform plan
terraform apply

And when the PO/Cliente/whatever approves and the feature is merged we will destroy this environment running terraform destroy ( #43 ).

The problem is when we create our PR the workspace doesn't even exist so I had added a variable called TF_WORKSPACE_FORCE_CREATE to be passed to plan action and create the new workspace on the fly.

If you find that it could be useful I'll open the PR.

I'm not sure of your exact use case, but the TF_WORKSPACE environment variable should already give you this behavior.

$ export TF_WORKSPACE=master
$ terraform init
...
$ terraform workspace show
master

In my testing, I found that this does not work when you are using the remote backend with the prefix configuration argument. Curious to see if this approach works with your use case.

You are completely right. I had made some tests here and looks that work for what I'm doing.
I'm not using prefix right now, but I had tested it using S3 as backend with prefix and I was able to use it without bigger issues.
I had to make some adjustments on the steps to work with the TF_WORKSPACE but it's awesome to know this variable. Thanks a lot.
In fact, it's a very hidden variable! 🤣
Thank you!
I'll close the PR and the issue ok?

Any idea what you have to do to get this working? I simply get the following:


Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.

The currently selected workspace (dev) does not exist.
  This is expected behavior when the selected workspace did not have an
  existing non-empty state. Please enter a number to select a workspace:
  
  1. default

  Enter a value: 

Error: Failed to select workspace: input not a valid number

My actions code:

  job1:
    runs-on: ubuntu-latest
    env:
      TF_ACTIONS_VERSION: 0.12.13
      TF_WORKSPACE: dev
      AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
      AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
    steps:
      - name: "Checkout"
        uses: actions/checkout@master
        with:
          ref: my-branch

      - name: "Terraform Init"
        uses: hashicorp/terraform-github-actions@master
        with:
          tf_actions_version: ${{ env.TF_ACTIONS_VERSION }}
          tf_actions_subcommand: "init"