0

I'm trying to store the states of my terraform workspaces in an array using shell.

I'm trying this way which usually works for me:

declare -a workspace_list=( $(terraform workspace list))

for a in $(seq 0 ${#workspace_list[*]})
do  
    if [[ -z ${workspace_list[$a]} ]]
        then  
              break
        fi
    echo $(($a+1))": "${workspace_list[$a]}
    a=$(($a+1))
done

However, it gives me an output with all the files in the directory as well along with the workspaces.

I'm guessing it's to do with the multiple args with terraform command. Please help.

Output of terraform workspace list for reference enter image description here

4
  • Could you print the output of "terraform workspace list" so that we can see the raw data ? Commented Feb 11, 2022 at 7:47
  • @Kendle added snapshot Commented Feb 11, 2022 at 7:51
  • What do you want to output? "dev-singapore"? Commented Feb 11, 2022 at 8:07
  • Use readarray/mapfile to populate an array with lines of a file/command output. Commented Feb 11, 2022 at 8:41

1 Answer 1

1

When you initialize the array with the result of terraform command it looks like:

declare -a workspace_list=( * default dev-singapore)

Here, * is glob-expanded to list of all files in current directory.

You can get rid of the asterisk just processing terraform's output.

declare -a workspace_list=($(terraform workspace list | sed 's/*//'))

Unfortunately unlike terraform plan, there is no option for JSON output from terraform workspace, which would be more clean.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.