Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

12.4 KB
Raw Blame
import { Controller, useFormContext, useWatch } from "react-hook-form";
import { Info } from "lucide-react";

import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/SecretSyncConnectionField";
import {
  Combobox,
  Field,
  FieldContent,
  FieldError,
  FieldGroup,
  FieldLabel,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from "@app/components/v3";
import {
  TERRAFORM_CLOUD_SYNC_SCOPES,
  TerraformCloudSyncCategory,
  TerraformCloudSyncScope,
  useTerraformCloudConnectionListOrganizations
} from "@app/hooks/api/appConnections/terraform-cloud";
import { SecretSync } from "@app/hooks/api/secretSyncs";

import { TSecretSyncForm } from "../schemas";

export const TerraformCloudSyncFields = () => {
  const { control, watch, setValue } = useFormContext<
    TSecretSyncForm & { destination: SecretSync.TerraformCloud }
  >();

  const connectionId = useWatch({ name: "connection.id", control });
  const currentOrg = watch("destinationConfig.org");
  const currentScope = watch("destinationConfig.scope");

  const { data: organizations = [], isPending: isOrganizationsPending } =
    useTerraformCloudConnectionListOrganizations(connectionId, {
      enabled: Boolean(connectionId)
    });

  const selectedOrg = organizations?.find((org) => org.id === currentOrg);
  const variableSets = selectedOrg?.variableSets || [];
  const workspaces = selectedOrg?.workspaces || [];

  return (
    <FieldGroup>
      <SecretSyncConnectionField
        onChange={() => {
          setValue("destinationConfig.org", "");
          setValue("destinationConfig.variableSetId", "");
          setValue("destinationConfig.workspaceId", "");
          setValue("destinationConfig.variableSetName", "");
          setValue("destinationConfig.workspaceName", "");
        }}
      />
      <Controller
        name="destinationConfig.org"
        control={control}
        render={({ field: { value, onChange }, fieldState: { error } }) => (
          <Field>
            <FieldLabel
              id="secret-sync-terraform-cloud-org-label"
              htmlFor="secret-sync-terraform-cloud-org"
            >
              Organization
            </FieldLabel>
            <FieldContent>
              <Combobox
                aria-labelledby="secret-sync-terraform-cloud-org-label"
                aria-describedby={error ? "secret-sync-terraform-cloud-org-error" : undefined}
                id="secret-sync-terraform-cloud-org"
                isError={Boolean(error)}
                isLoading={isOrganizationsPending && Boolean(connectionId)}
                isDisabled={!connectionId}
                value={
                  organizations ? (organizations.find((org) => org.id === value) ?? null) : null
                }
                onValueChange={(option) => {
                  onChange(option?.id ?? null);
                  setValue("destinationConfig.variableSetId", "");
                  setValue("destinationConfig.workspaceId", "");
                  setValue("destinationConfig.variableSetName", "");
                  setValue("destinationConfig.workspaceName", "");
                }}
                options={organizations}
                placeholder="Select an organization..."
                getOptionLabel={(option) => option.name}
                getOptionValue={(option) => option.id.toString()}
                getOptionKeywords={(option) => [option.id.toString()]}
                modal
              />
              <FieldError id="secret-sync-terraform-cloud-org-error" errors={[error]} />
            </FieldContent>
          </Field>
        )}
      />
      <Controller
        name="destinationConfig.category"
        control={control}
        defaultValue={TerraformCloudSyncCategory.Environment}
        render={({ field: { value, onChange }, fieldState: { error } }) => (
          <Field>
            <FieldLabel>
              Category
              <Tooltip>
                <TooltipTrigger asChild>
                  <Info />
                </TooltipTrigger>
                <TooltipContent className="max-w-lg">
                  <ul className="flex list-disc flex-col gap-3 pl-4">
                    <li>
                      <p className="text-label">
                        <span className="font-medium text-foreground-soft">
                          Environment variables configure Terraform&apos;s behavior (e.g.,
                          credentials).
                        </span>
                      </p>
                    </li>
                    <li>
                      <p className="text-label">
                        <span className="font-medium text-foreground-soft">
                          Terraform variables are used as input values in your configuration.
                        </span>
                      </p>
                    </li>
                  </ul>
                </TooltipContent>
              </Tooltip>
            </FieldLabel>
            <FieldContent>
              <Select
                value={value}
                onValueChange={onChange}
                defaultValue={TerraformCloudSyncCategory.Environment}
              >
                <SelectTrigger className="w-full capitalize" isError={Boolean(error)}>
                  <SelectValue placeholder="Select category..." />
                </SelectTrigger>
                <SelectContent position="popper">
                  {Object.entries(TerraformCloudSyncCategory).map(([envKey, envValue]) => (
                    <SelectItem className="capitalize" value={envValue} key={envValue}>
                      {envKey.replace("-", " ")}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FieldError errors={[error]} />
            </FieldContent>
          </Field>
        )}
      />
      <Controller
        name="destinationConfig.scope"
        control={control}
        defaultValue={TerraformCloudSyncScope.VariableSet}
        render={({ field: { value, onChange }, fieldState: { error } }) => (
          <Field>
            <FieldLabel>
              Scope
              <Tooltip>
                <TooltipTrigger asChild>
                  <Info />
                </TooltipTrigger>
                <TooltipContent className="max-w-lg">
                  <div className="flex flex-col gap-3">
                    <p>
                      Specify how Infisical should manage secrets from Terraform Cloud. The
                      following options are available:
                    </p>
                    <ul className="flex list-disc flex-col gap-3 pl-4">
                      {Object.values(TERRAFORM_CLOUD_SYNC_SCOPES).map(({ name, description }) => (
                        <li key={name}>
                          <p className="text-label">
                            <span className="font-medium text-foreground-soft">{name}</span>:{" "}
                            {description}
                          </p>
                        </li>
                      ))}
                    </ul>
                  </div>
                </TooltipContent>
              </Tooltip>
            </FieldLabel>
            <FieldContent>
              <Select
                value={value}
                onValueChange={(val) => {
                  onChange(val);
                  setValue("destinationConfig.variableSetId", "");
                  setValue("destinationConfig.workspaceId", "");
                  setValue("destinationConfig.variableSetName", "");
                  setValue("destinationConfig.workspaceName", "");
                }}
              >
                <SelectTrigger className="w-full capitalize" isError={Boolean(error)}>
                  <SelectValue placeholder="Select a scope..." />
                </SelectTrigger>
                <SelectContent position="popper">
                  {Object.values(TerraformCloudSyncScope).map((scope) => (
                    <SelectItem className="capitalize" value={scope} key={scope}>
                      {scope.replace("-", " ")}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FieldError errors={[error]} />
            </FieldContent>
          </Field>
        )}
      />
      {currentScope === TerraformCloudSyncScope.VariableSet && (
        <Controller
          name="destinationConfig.variableSetId"
          control={control}
          render={({ field: { value, onChange }, fieldState: { error } }) => (
            <Field>
              <FieldLabel
                id="secret-sync-terraform-cloud-variable-set-id-label"
                htmlFor="secret-sync-terraform-cloud-variable-set-id"
              >
                Variable Set
              </FieldLabel>
              <FieldContent>
                <Combobox
                  aria-labelledby="secret-sync-terraform-cloud-variable-set-id-label"
                  aria-describedby={
                    error ? "secret-sync-terraform-cloud-variable-set-id-error" : undefined
                  }
                  id="secret-sync-terraform-cloud-variable-set-id"
                  isError={Boolean(error)}
                  isLoading={isOrganizationsPending && Boolean(connectionId) && Boolean(currentOrg)}
                  isDisabled={!connectionId || !currentOrg}
                  value={variableSets.find((variableSet) => variableSet.id === value) ?? null}
                  onValueChange={(option) => {
                    const selectedOption = option;
                    onChange(selectedOption?.id ?? null);

                    if (selectedOption) {
                      setValue("destinationConfig.variableSetName", selectedOption.name);
                    } else {
                      setValue("destinationConfig.variableSetName", "");
                    }
                  }}
                  options={variableSets}
                  placeholder="Select a variable set..."
                  getOptionLabel={(option) => option.name}
                  getOptionValue={(option) => option.id.toString()}
                  getOptionKeywords={(option) => [option.id.toString()]}
                  modal
                />
                <FieldError
                  id="secret-sync-terraform-cloud-variable-set-id-error"
                  errors={[error]}
                />
              </FieldContent>
            </Field>
          )}
        />
      )}
      {currentScope === TerraformCloudSyncScope.Workspace && (
        <Controller
          name="destinationConfig.workspaceId"
          control={control}
          render={({ field: { value, onChange }, fieldState: { error } }) => (
            <Field>
              <FieldLabel
                id="secret-sync-terraform-cloud-workspace-id-label"
                htmlFor="secret-sync-terraform-cloud-workspace-id"
              >
                Workspace
              </FieldLabel>
              <FieldContent>
                <Combobox
                  aria-labelledby="secret-sync-terraform-cloud-workspace-id-label"
                  aria-describedby={
                    error ? "secret-sync-terraform-cloud-workspace-id-error" : undefined
                  }
                  id="secret-sync-terraform-cloud-workspace-id"
                  isError={Boolean(error)}
                  isLoading={isOrganizationsPending && Boolean(connectionId) && Boolean(currentOrg)}
                  isDisabled={!connectionId || !currentOrg}
                  value={workspaces.find((workspace) => workspace.id === value) ?? null}
                  onValueChange={(option) => {
                    const selectedOption = option;
                    onChange(selectedOption?.id ?? null);

                    if (selectedOption) {
                      setValue("destinationConfig.workspaceName", selectedOption.name);
                    } else {
                      setValue("destinationConfig.workspaceName", "");
                    }
                  }}
                  options={workspaces}
                  placeholder="Select a workspace..."
                  getOptionLabel={(option) => option.name}
                  getOptionValue={(option) => option.id.toString()}
                  getOptionKeywords={(option) => [option.id.toString()]}
                  modal
                />
                <FieldError id="secret-sync-terraform-cloud-workspace-id-error" errors={[error]} />
              </FieldContent>
            </Field>
          )}
        />
      )}
    </FieldGroup>
  );
};