Skip to content

Instantly share code, notes, and snippets.

@SafeEval
Created August 14, 2024 04:02

Revisions

  1. SafeEval created this gist Aug 14, 2024.
    55 changes: 55 additions & 0 deletions update-tfc-workspace-vcs-config.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    #!/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