Skip to content

docs: clarify cron attribute format for coder_script resource #409

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
19 changes: 15 additions & 4 deletions docs/resources/script.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,26 @@ resource "coder_script" "code-server" {
})
}

resource "coder_script" "nightly_sleep_reminder" {
resource "coder_script" "nightly_update" {
agent_id = coder_agent.dev.agent_id
display_name = "Nightly update"
icon = "/icon/database.svg"
cron = "0 22 * * *"
cron = "0 0 22 * * *" # Run at 22:00 (10 PM) every day
script = <<EOF
#!/bin/sh
echo "Running nightly update"
sudo apt-get install
sudo apt-get update
EOF
}

resource "coder_script" "every_5_minutes" {
agent_id = coder_agent.dev.agent_id
display_name = "Health check"
icon = "/icon/heart.svg"
cron = "0 */5 * * * *" # Run every 5 minutes
script = <<EOF
#!/bin/sh
echo "Health check at $(date)"
EOF
}

Expand All @@ -78,7 +89,7 @@ resource "coder_script" "shutdown" {

### Optional

- `cron` (String) The cron schedule to run the script on. This is a cron expression.
- `cron` (String) The cron schedule to run the script on. This uses a 6-field cron expression format: `seconds minutes hours day-of-month month day-of-week`. Note that this differs from the standard Unix 5-field format by including seconds as the first field. Examples: `"0 0 22 * * *"` (daily at 10 PM), `"0 */5 * * * *"` (every 5 minutes), `"30 0 9 * * 1-5"` (weekdays at 9:30 AM).
- `icon` (String) A URL to an icon that will display in the dashboard. View built-in icons [here](https://github.com/coder/coder/tree/main/site/static/icon). Use a built-in icon with `"${data.coder_workspace.me.access_url}/icon/<path>"`.
- `log_path` (String) The path of a file to write the logs to. If relative, it will be appended to tmp.
- `run_on_start` (Boolean) This option defines whether or not the script should run when the agent starts. The script should exit when it is done to signal that the agent is ready.
Expand Down
17 changes: 14 additions & 3 deletions examples/resources/coder_script/resource.tf
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,26 @@ resource "coder_script" "code-server" {
})
}

resource "coder_script" "nightly_sleep_reminder" {
resource "coder_script" "nightly_update" {
agent_id = coder_agent.dev.agent_id
display_name = "Nightly update"
icon = "/icon/database.svg"
cron = "0 22 * * *"
cron = "0 0 22 * * *" # Run at 22:00 (10 PM) every day
script = <<EOF
#!/bin/sh
echo "Running nightly update"
sudo apt-get install
sudo apt-get update
EOF
}

resource "coder_script" "every_5_minutes" {
agent_id = coder_agent.dev.agent_id
display_name = "Health check"
icon = "/icon/heart.svg"
cron = "0 */5 * * * *" # Run every 5 minutes
script = <<EOF
#!/bin/sh
echo "Health check at $(date)"
EOF
}

Expand Down
35 changes: 29 additions & 6 deletions provider/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package provider
import (
"context"
"fmt"
"strings"

"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
Expand All @@ -13,6 +14,32 @@ import (

var ScriptCRONParser = cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)

// ValidateCronExpression validates a cron expression and provides helpful warnings for common mistakes
func ValidateCronExpression(cronExpr string) (warnings []string, errors []error) {
// Check if it looks like a 5-field Unix cron expression
fields := strings.Fields(cronExpr)
if len(fields) == 5 {
// Try to parse as standard Unix cron (without seconds)
unixParser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
if _, err := unixParser.Parse(cronExpr); err == nil {
// It's a valid 5-field expression, provide a helpful warning
warnings = append(warnings, fmt.Sprintf(
"The cron expression '%s' appears to be in Unix 5-field format. "+
"Coder uses 6-field format (seconds minutes hours day month day-of-week). "+
"Consider prefixing with '0 ' to run at the start of each minute: '0 %s'",
cronExpr, cronExpr))
}
}

// Validate with the actual 6-field parser
_, err := ScriptCRONParser.Parse(cronExpr)
if err != nil {
errors = append(errors, fmt.Errorf("%s is not a valid cron expression: %w", cronExpr, err))
}

return warnings, errors
}

func scriptResource() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
Expand Down Expand Up @@ -72,17 +99,13 @@ func scriptResource() *schema.Resource {
ForceNew: true,
Type: schema.TypeString,
Optional: true,
Description: "The cron schedule to run the script on. This is a cron expression.",
Description: "The cron schedule to run the script on. This uses a 6-field cron expression format: `seconds minutes hours day-of-month month day-of-week`. Note that this differs from the standard Unix 5-field format by including seconds as the first field. Examples: `\"0 0 22 * * *\"` (daily at 10 PM), `\"0 */5 * * * *\"` (every 5 minutes), `\"30 0 9 * * 1-5\"` (weekdays at 9:30 AM).",
ValidateFunc: func(i interface{}, _ string) ([]string, []error) {
v, ok := i.(string)
if !ok {
return []string{}, []error{fmt.Errorf("got type %T instead of string", i)}
}
_, err := ScriptCRONParser.Parse(v)
if err != nil {
return []string{}, []error{fmt.Errorf("%s is not a valid cron expression: %w", v, err)}
}
return nil, nil
return ValidateCronExpression(v)
},
},
"start_blocks_login": {
Expand Down
72 changes: 72 additions & 0 deletions provider/script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"

"github.com/coder/terraform-provider-coder/v2/provider"
)

func TestScript(t *testing.T) {
Expand Down Expand Up @@ -124,3 +126,73 @@ func TestScriptStartBlocksLoginRequiresRunOnStart(t *testing.T) {
}},
})
}

func TestValidateCronExpression(t *testing.T) {
t.Parallel()

tests := []struct {
name string
cronExpr string
expectWarnings bool
expectErrors bool
warningContains string
}{
{
name: "valid 6-field expression",
cronExpr: "0 0 22 * * *",
expectWarnings: false,
expectErrors: false,
},
{
name: "valid 6-field expression with seconds",
cronExpr: "30 0 9 * * 1-5",
expectWarnings: false,
expectErrors: false,
},
{
name: "5-field Unix format - should warn",
cronExpr: "0 22 * * *",
expectWarnings: true,
expectErrors: false,
warningContains: "appears to be in Unix 5-field format",
},
{
name: "5-field every 5 minutes - should warn",
cronExpr: "*/5 * * * *",
expectWarnings: true,
expectErrors: false,
warningContains: "Consider prefixing with '0 '",
},
{
name: "invalid expression",
cronExpr: "invalid",
expectErrors: true,
},
{
name: "too many fields",
cronExpr: "0 0 0 0 0 0 0",
expectErrors: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
warnings, errors := provider.ValidateCronExpression(tt.cronExpr)

if tt.expectWarnings {
require.NotEmpty(t, warnings, "Expected warnings but got none")
if tt.warningContains != "" {
require.Contains(t, warnings[0], tt.warningContains)
}
} else {
require.Empty(t, warnings, "Expected no warnings but got: %v", warnings)
}

if tt.expectErrors {
require.NotEmpty(t, errors, "Expected errors but got none")
} else {
require.Empty(t, errors, "Expected no errors but got: %v", errors)
}
})
}
}
Loading