Created
August 14, 2024 04:02
-
-
Save SafeEval/f56a802a2dc13c5d789049d10c1a1ad7 to your computer and use it in GitHub Desktop.
Update a set of TFC workspace VCS configs to use a Github App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Connect a TFC workspace to a Github VCS provider using the TFC API. | |
INFILE_WORKSPACES="tfc-workspace-name-list.txt" | |
function check_env() { | |
var_name="$1" | |
var_value="$2" | |
if [ -z "$var_value" ]; then | |
echo "Missing $var_name environment variable"; | |
exit 1; | |
fi | |
} | |
check_env "TFC_API_TOKEN" "$TFC_API_TOKEN" | |
check_env "TFC_ORGANIZATION_NAME" "$TFC_ORGANIZATION_NAME" | |
check_env "VCS_REPO_IDENTIFIER" "$VCS_REPO_IDENTIFIER" # <org>/<repo> | |
check_env "GITHUB_APP_INSTALLATION_ID" "$GITHUB_APP_INSTALLATION_ID" # ghain-XXXXXXXXXX | |
# JSON payload to update the VCS repository settings | |
UPDATE_PAYLOAD=$(cat <<EOF | |
{ | |
"data": { | |
"attributes": { | |
"vcs-repo": { | |
"identifier": "${VCS_REPO_IDENTIFIER}", | |
"github-app-installation-id": "${GITHUB_APP_INSTALLATION_ID}" | |
} | |
} | |
} | |
} | |
EOF | |
) | |
for TFC_WORKSPACE_NAME in $(cat $INFILE_WORKSPACES); do | |
# API endpoint to update the workspace | |
API_URL="https://app.terraform.io/api/v2/organizations/${TFC_ORGANIZATION_NAME}/workspaces/${TFC_WORKSPACE_NAME}" | |
echo "Request URL: $API_URL" | |
# Make the API request using curl | |
response=$(curl -s \ | |
-X PATCH \ | |
--url "${API_URL}" \ | |
--header "Authorization: Bearer ${TFC_API_TOKEN}" \ | |
--header "Content-Type: application/vnd.api+json" \ | |
--data "${UPDATE_PAYLOAD}") | |
# Output the response | |
echo "Response from Terraform Cloud API:" | |
echo "${response}" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment