Skip to content

feat: Update Terraform provider to support "dir" in "coder_agent" #1219

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ type Metadata struct {
OwnerUsername string `json:"owner_username"`
EnvironmentVariables map[string]string `json:"environment_variables"`
StartupScript string `json:"startup_script"`
Directory string `json:"directory"`
}

type Dialer func(ctx context.Context, logger slog.Logger) (Metadata, *peerbroker.Listener, error)
Expand Down Expand Up @@ -340,6 +341,11 @@ func (a *agent) createCommand(ctx context.Context, rawCommand string, env []stri
caller = "/c"
}
cmd := exec.CommandContext(ctx, shell, caller, command)
cmd.Dir = metadata.Directory
if cmd.Dir == "" {
// Default to $HOME if a directory is not set!
cmd.Dir = os.Getenv("HOME")
}
cmd.Env = append(os.Environ(), env...)
executablePath, err := os.Executable()
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -1173,6 +1173,7 @@ func (q *fakeQuerier) InsertWorkspaceAgent(_ context.Context, arg database.Inser
Name: arg.Name,
Architecture: arg.Architecture,
OperatingSystem: arg.OperatingSystem,
Directory: arg.Directory,
StartupScript: arg.StartupScript,
InstanceMetadata: arg.InstanceMetadata,
ResourceMetadata: arg.ResourceMetadata,
Expand Down
3 changes: 2 additions & 1 deletion coderd/database/dump.sql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions coderd/database/migrations/000009_agent_directory.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE ONLY workspace_agents
DROP COLUMN IF EXISTS directory;
3 changes: 3 additions & 0 deletions coderd/database/migrations/000009_agent_directory.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ALTER TABLE ONLY workspace_agents
-- UNIX paths are a maximum length of 4096.
ADD COLUMN IF NOT EXISTS directory varchar(4096) DEFAULT '' NOT NULL;
1 change: 1 addition & 0 deletions coderd/database/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 13 additions & 5 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion coderd/database/queries/workspaceagents.sql
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,12 @@ INSERT INTO
environment_variables,
operating_system,
startup_script,
directory,
instance_metadata,
resource_metadata
)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING *;
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING *;

-- name: UpdateWorkspaceAgentConnectionByID :exec
UPDATE
Expand Down
3 changes: 3 additions & 0 deletions coderd/provisionerdaemons.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ func (server *provisionerdServer) AcquireJob(ctx context.Context, _ *proto.Empty
WorkspaceTransition: transition,
WorkspaceName: workspace.Name,
WorkspaceOwner: owner.Username,
WorkspaceId: workspace.ID.String(),
WorkspaceOwnerId: owner.ID.String(),
},
},
}
Expand Down Expand Up @@ -633,6 +635,7 @@ func insertWorkspaceResource(ctx context.Context, db database.Store, jobID uuid.
AuthInstanceID: instanceID,
Architecture: agent.Architecture,
EnvironmentVariables: env,
Directory: agent.Directory,
OperatingSystem: agent.OperatingSystem,
StartupScript: sql.NullString{
String: agent.StartupScript,
Expand Down
2 changes: 2 additions & 0 deletions coderd/workspaceagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ func (api *api) workspaceAgentMetadata(rw http.ResponseWriter, r *http.Request)
OwnerUsername: owner.Username,
EnvironmentVariables: apiAgent.EnvironmentVariables,
StartupScript: apiAgent.StartupScript,
Directory: apiAgent.Directory,
})
}

Expand Down Expand Up @@ -469,6 +470,7 @@ func convertWorkspaceAgent(dbAgent database.WorkspaceAgent, agentUpdateFrequency
OperatingSystem: dbAgent.OperatingSystem,
StartupScript: dbAgent.StartupScript.String,
EnvironmentVariables: envs,
Directory: dbAgent.Directory,
}
if dbAgent.FirstConnectedAt.Valid {
workspaceAgent.FirstConnectedAt = &dbAgent.FirstConnectedAt.Time
Expand Down
74 changes: 43 additions & 31 deletions coderd/workspaceagents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package coderd_test
import (
"context"
"encoding/json"
"runtime"
"strings"
"testing"

Expand All @@ -22,40 +23,45 @@ import (

func TestWorkspaceAgent(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
user := coderdtest.CreateFirstUser(t, client)
daemonCloser := coderdtest.NewProvisionerDaemon(t, client)
authToken := uuid.NewString()
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
Parse: echo.ParseComplete,
ProvisionDryRun: echo.ProvisionComplete,
Provision: []*proto.Provision_Response{{
Type: &proto.Provision_Response_Complete{
Complete: &proto.Provision_Complete{
Resources: []*proto.Resource{{
Name: "example",
Type: "aws_instance",
Agents: []*proto.Agent{{
Id: uuid.NewString(),
Auth: &proto.Agent_Token{
Token: authToken,
},
t.Run("Connect", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
user := coderdtest.CreateFirstUser(t, client)
daemonCloser := coderdtest.NewProvisionerDaemon(t, client)
authToken := uuid.NewString()
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, &echo.Responses{
Parse: echo.ParseComplete,
ProvisionDryRun: echo.ProvisionComplete,
Provision: []*proto.Provision_Response{{
Type: &proto.Provision_Response_Complete{
Complete: &proto.Provision_Complete{
Resources: []*proto.Resource{{
Name: "example",
Type: "aws_instance",
Agents: []*proto.Agent{{
Id: uuid.NewString(),
Directory: "/tmp",
Auth: &proto.Agent_Token{
Token: authToken,
},
}},
}},
}},
},
},
},
}},
}},
})
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID)
coderdtest.AwaitWorkspaceBuildJob(t, client, workspace.LatestBuild.ID)
daemonCloser.Close()

resources, err := client.WorkspaceResourcesByBuild(context.Background(), workspace.LatestBuild.ID)
require.NoError(t, err)
require.Equal(t, "/tmp", resources[0].Agents[0].Directory)
_, err = client.WorkspaceAgent(context.Background(), resources[0].Agents[0].ID)
require.NoError(t, err)
})
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID)
coderdtest.AwaitWorkspaceBuildJob(t, client, workspace.LatestBuild.ID)
daemonCloser.Close()

resources, err := client.WorkspaceResourcesByBuild(context.Background(), workspace.LatestBuild.ID)
require.NoError(t, err)
_, err = client.WorkspaceAgent(context.Background(), resources[0].Agents[0].ID)
require.NoError(t, err)
}

func TestWorkspaceAgentListen(t *testing.T) {
Expand Down Expand Up @@ -165,6 +171,12 @@ func TestWorkspaceAgentTURN(t *testing.T) {

func TestWorkspaceAgentPTY(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
// This might be our implementation, or ConPTY itself.
// It's difficult to find extensive tests for it, so
// it seems like it could be either.
t.Skip("ConPTY appears to be inconsistent on Windows.")
}
client := coderdtest.New(t, nil)
user := coderdtest.CreateFirstUser(t, client)
daemonCloser := coderdtest.NewProvisionerDaemon(t, client)
Expand Down
1 change: 1 addition & 0 deletions codersdk/workspaceresources.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type WorkspaceAgent struct {
EnvironmentVariables map[string]string `json:"environment_variables"`
OperatingSystem string `json:"operating_system"`
StartupScript string `json:"startup_script,omitempty"`
Directory string `json:"directory,omitempty"`
}

type WorkspaceAgentResourceMetadata struct {
Expand Down
10 changes: 10 additions & 0 deletions provisioner/terraform/provision.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ func (t *terraform) Provision(stream proto.DRPCProvisioner_ProvisionStream) erro
"CODER_WORKSPACE_TRANSITION="+strings.ToLower(start.Metadata.WorkspaceTransition.String()),
"CODER_WORKSPACE_NAME="+start.Metadata.WorkspaceName,
"CODER_WORKSPACE_OWNER="+start.Metadata.WorkspaceOwner,
"CODER_WORKSPACE_ID="+start.Metadata.WorkspaceId,
"CODER_WORKSPACE_OWNER_ID="+start.Metadata.WorkspaceOwnerId,
)
for key, value := range provisionersdk.AgentScriptEnv() {
env = append(env, key+"="+value)
Expand Down Expand Up @@ -330,6 +332,12 @@ func parseTerraformPlan(ctx context.Context, terraform *tfexec.Terraform, planfi
agent.StartupScript = startupScript
}
}
if directoryRaw, has := resource.Expressions["dir"]; has {
dir, ok := directoryRaw.ConstantValue.(string)
if ok {
agent.Directory = dir
}
}

agents[resource.Address] = agent
}
Expand Down Expand Up @@ -381,6 +389,7 @@ func parseTerraformApply(ctx context.Context, terraform *tfexec.Terraform, state
Auth string `mapstructure:"auth"`
OperatingSystem string `mapstructure:"os"`
Architecture string `mapstructure:"arch"`
Directory string `mapstructure:"dir"`
ID string `mapstructure:"id"`
Token string `mapstructure:"token"`
Env map[string]string `mapstructure:"env"`
Expand All @@ -405,6 +414,7 @@ func parseTerraformApply(ctx context.Context, terraform *tfexec.Terraform, state
StartupScript: attrs.StartupScript,
OperatingSystem: attrs.OperatingSystem,
Architecture: attrs.Architecture,
Directory: attrs.Directory,
}
switch attrs.Auth {
case "token":
Expand Down
2 changes: 2 additions & 0 deletions provisioner/terraform/provision_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ provider "coder" {
resource "coder_agent" "A" {
os = "windows"
arch = "arm64"
dir = "C:\\System32"
}
resource "null_resource" "A" {
depends_on = [
Expand All @@ -184,6 +185,7 @@ provider "coder" {
Name: "A",
OperatingSystem: "windows",
Architecture: "arm64",
Directory: "C:\\System32",
Auth: &proto.Agent_Token{
Token: "",
},
Expand Down
Loading