Skip to content

Commit 9e0f3d1

Browse files
abborgjamengualX-Guardian
authored
feat: Support project-level Terraform distribution selection (#5167)
Signed-off-by: Andrew Borg <[email protected]> Co-authored-by: PePe Amengual <[email protected]> Co-authored-by: Simon Heather <[email protected]>
1 parent a9c3730 commit 9e0f3d1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+1325
-411
lines changed

Diff for: cmd/server.go

+25-12
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ const (
7272
CheckoutStrategyFlag = "checkout-strategy"
7373
ConfigFlag = "config"
7474
DataDirFlag = "data-dir"
75+
DefaultTFDistributionFlag = "default-tf-distribution"
7576
DefaultTFVersionFlag = "default-tf-version"
7677
DisableApplyAllFlag = "disable-apply-all"
7778
DisableAutoplanFlag = "disable-autoplan"
@@ -141,7 +142,7 @@ const (
141142
SSLCertFileFlag = "ssl-cert-file"
142143
SSLKeyFileFlag = "ssl-key-file"
143144
RestrictFileList = "restrict-file-list"
144-
TFDistributionFlag = "tf-distribution"
145+
TFDistributionFlag = "tf-distribution" // deprecated for DefaultTFDistributionFlag
145146
TFDownloadFlag = "tf-download"
146147
TFDownloadURLFlag = "tf-download-url"
147148
UseTFPluginCache = "use-tf-plugin-cache"
@@ -421,8 +422,8 @@ var stringFlags = map[string]stringFlag{
421422
description: fmt.Sprintf("File containing x509 private key matching --%s.", SSLCertFileFlag),
422423
},
423424
TFDistributionFlag: {
424-
description: fmt.Sprintf("Which TF distribution to use. Can be set to %s or %s.", TFDistributionTerraform, TFDistributionOpenTofu),
425-
defaultValue: DefaultTFDistribution,
425+
description: "[Deprecated for --default-tf-distribution].",
426+
hidden: true,
426427
},
427428
TFDownloadURLFlag: {
428429
description: "Base URL to download Terraform versions from.",
@@ -437,6 +438,10 @@ var stringFlags = map[string]stringFlag{
437438
" Only set if using TFC/E as a remote backend." +
438439
" Should be specified via the ATLANTIS_TFE_TOKEN environment variable for security.",
439440
},
441+
DefaultTFDistributionFlag: {
442+
description: fmt.Sprintf("Which TF distribution to use. Can be set to %s or %s.", TFDistributionTerraform, TFDistributionOpenTofu),
443+
defaultValue: DefaultTFDistribution,
444+
},
440445
DefaultTFVersionFlag: {
441446
description: "Terraform version to default to (ex. v0.12.0). Will download if not yet on disk." +
442447
" If not set, Atlantis uses the terraform binary in its PATH.",
@@ -840,12 +845,13 @@ func (s *ServerCmd) run() error {
840845

841846
// Config looks good. Start the server.
842847
server, err := s.ServerCreator.NewServer(userConfig, server.Config{
843-
AllowForkPRsFlag: AllowForkPRsFlag,
844-
AtlantisURLFlag: AtlantisURLFlag,
845-
AtlantisVersion: s.AtlantisVersion,
846-
DefaultTFVersionFlag: DefaultTFVersionFlag,
847-
RepoConfigJSONFlag: RepoConfigJSONFlag,
848-
SilenceForkPRErrorsFlag: SilenceForkPRErrorsFlag,
848+
AllowForkPRsFlag: AllowForkPRsFlag,
849+
AtlantisURLFlag: AtlantisURLFlag,
850+
AtlantisVersion: s.AtlantisVersion,
851+
DefaultTFDistributionFlag: DefaultTFDistributionFlag,
852+
DefaultTFVersionFlag: DefaultTFVersionFlag,
853+
RepoConfigJSONFlag: RepoConfigJSONFlag,
854+
SilenceForkPRErrorsFlag: SilenceForkPRErrorsFlag,
849855
})
850856

851857
if err != nil {
@@ -921,8 +927,11 @@ func (s *ServerCmd) setDefaults(c *server.UserConfig, v *viper.Viper) {
921927
if c.RedisPort == 0 {
922928
c.RedisPort = DefaultRedisPort
923929
}
924-
if c.TFDistribution == "" {
925-
c.TFDistribution = DefaultTFDistribution
930+
if c.TFDistribution != "" && c.DefaultTFDistribution == "" {
931+
c.DefaultTFDistribution = c.TFDistribution
932+
}
933+
if c.DefaultTFDistribution == "" {
934+
c.DefaultTFDistribution = DefaultTFDistribution
926935
}
927936
if c.TFDownloadURL == "" {
928937
c.TFDownloadURL = DefaultTFDownloadURL
@@ -953,7 +962,7 @@ func (s *ServerCmd) validate(userConfig server.UserConfig) error {
953962
return fmt.Errorf("invalid log level: must be one of %v", ValidLogLevels)
954963
}
955964

956-
if userConfig.TFDistribution != TFDistributionTerraform && userConfig.TFDistribution != TFDistributionOpenTofu {
965+
if userConfig.DefaultTFDistribution != TFDistributionTerraform && userConfig.DefaultTFDistribution != TFDistributionOpenTofu {
957966
return fmt.Errorf("invalid tf distribution: expected one of %s or %s",
958967
TFDistributionTerraform, TFDistributionOpenTofu)
959968
}
@@ -1172,6 +1181,10 @@ func (s *ServerCmd) deprecationWarnings(userConfig *server.UserConfig) error {
11721181
// }
11731182
//
11741183

1184+
if userConfig.TFDistribution != "" {
1185+
deprecatedFlags = append(deprecatedFlags, TFDistributionFlag)
1186+
}
1187+
11751188
if len(deprecatedFlags) > 0 {
11761189
warning := "WARNING: "
11771190
if len(deprecatedFlags) == 1 {

Diff for: cmd/server_test.go

+41
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ var testFlags = map[string]interface{}{
7373
CheckoutStrategyFlag: CheckoutStrategyMerge,
7474
CheckoutDepthFlag: 0,
7575
DataDirFlag: "/path",
76+
DefaultTFDistributionFlag: "terraform",
7677
DefaultTFVersionFlag: "v0.11.0",
7778
DisableApplyAllFlag: true,
7879
DisableMarkdownFoldingFlag: true,
@@ -977,6 +978,46 @@ func TestExecute_AutoplanFileList(t *testing.T) {
977978
}
978979
}
979980

981+
func TestExecute_ValidateDefaultTFDistribution(t *testing.T) {
982+
cases := []struct {
983+
description string
984+
flags map[string]interface{}
985+
expectErr string
986+
}{
987+
{
988+
"terraform",
989+
map[string]interface{}{
990+
DefaultTFDistributionFlag: "terraform",
991+
},
992+
"",
993+
},
994+
{
995+
"opentofu",
996+
map[string]interface{}{
997+
DefaultTFDistributionFlag: "opentofu",
998+
},
999+
"",
1000+
},
1001+
{
1002+
"errs on invalid distribution",
1003+
map[string]interface{}{
1004+
DefaultTFDistributionFlag: "invalid_distribution",
1005+
},
1006+
"invalid tf distribution: expected one of terraform or opentofu",
1007+
},
1008+
}
1009+
for _, testCase := range cases {
1010+
t.Log("Should validate default tf distribution when " + testCase.description)
1011+
c := setupWithDefaults(testCase.flags, t)
1012+
err := c.Execute()
1013+
if testCase.expectErr != "" {
1014+
ErrEquals(t, testCase.expectErr, err)
1015+
} else {
1016+
Ok(t, err)
1017+
}
1018+
}
1019+
}
1020+
9801021
func setup(flags map[string]interface{}, t *testing.T) *cobra.Command {
9811022
vipr := viper.New()
9821023
for k, v := range flags {

Diff for: runatlantis.io/docs/repo-level-atlantis-yaml.md

+15
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ projects:
6666
branch: /main/
6767
dir: .
6868
workspace: default
69+
terraform_distribution: terraform
6970
terraform_version: v0.11.0
7071
delete_source_branch_on_merge: true
7172
repo_locking: true # deprecated: use repo_locks instead
@@ -262,6 +263,20 @@ See [Custom Workflow Use Cases: Terragrunt](custom-workflows.md#terragrunt)
262263

263264
See [Custom Workflow Use Cases: Running custom commands](custom-workflows.md#running-custom-commands)
264265

266+
### Terraform Distributions
267+
268+
If you'd like to use a different distribution of Terraform than what is set
269+
by the `--default-tf-version` flag, then set the `terraform_distribution` key:
270+
271+
```yaml
272+
version: 3
273+
projects:
274+
- dir: project1
275+
terraform_distribution: opentofu
276+
```
277+
278+
Atlantis will automatically download and use this distribution. Valid values are `terraform` and `opentofu`.
279+
265280
### Terraform Versions
266281

267282
If you'd like to use a different version of Terraform than what is in Atlantis'

Diff for: runatlantis.io/docs/server-configuration.md

+12-7
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,16 @@ and set `--autoplan-modules` to `false`.
386386
Note that the atlantis user is restricted to `~/.atlantis`.
387387
If you set the `--data-dir` flag to a path outside of Atlantis its home directory, ensure that you grant the atlantis user the correct permissions.
388388

389+
### `--default-tf-distribution`
390+
391+
```bash
392+
atlantis server --default-tf-distribution="terraform"
393+
# or
394+
ATLANTIS_DEFAULT_TF_DISTRIBUTION="terraform"
395+
```
396+
397+
Which TF distribution to use. Can be set to `terraform` or `opentofu`.
398+
389399
### `--default-tf-version`
390400

391401
```bash
@@ -1259,13 +1269,8 @@ This is useful when you have many projects and want to keep the pull request cle
12591269

12601270
### `--tf-distribution`
12611271

1262-
```bash
1263-
atlantis server --tf-distribution="terraform"
1264-
# or
1265-
ATLANTIS_TF_DISTRIBUTION="terraform"
1266-
```
1267-
1268-
Which TF distribution to use. Can be set to `terraform` or `opentofu`.
1272+
<Badge text="Deprecated" type="warn"/>
1273+
Deprecated for `--default-tf-distribution`.
12691274

12701275
### `--tf-download`
12711276

Diff for: server/controllers/events/events_controller_e2e_test.go

+12-6
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929
mock_policy "github.com/runatlantis/atlantis/server/core/runtime/policy/mocks"
3030
"github.com/runatlantis/atlantis/server/core/terraform"
3131
terraform_mocks "github.com/runatlantis/atlantis/server/core/terraform/mocks"
32+
"github.com/runatlantis/atlantis/server/core/terraform/tfclient"
3233
"github.com/runatlantis/atlantis/server/events"
3334
"github.com/runatlantis/atlantis/server/events/command"
3435
"github.com/runatlantis/atlantis/server/events/mocks"
@@ -1319,7 +1320,7 @@ func setupE2E(t *testing.T, repoDir string, opt setupOption) (events_controllers
13191320
mockDownloader := terraform_mocks.NewMockDownloader()
13201321
distribution := terraform.NewDistributionTerraformWithDownloader(mockDownloader)
13211322

1322-
terraformClient, err := terraform.NewClient(logger, distribution, binDir, cacheDir, "", "", "", "default-tf-version", "https://releases.hashicorp.com", true, false, projectCmdOutputHandler)
1323+
terraformClient, err := tfclient.NewClient(logger, distribution, binDir, cacheDir, "", "", "", "default-tf-version", "https://releases.hashicorp.com", true, false, projectCmdOutputHandler)
13231324
Ok(t, err)
13241325
boltdb, err := db.New(dataDir)
13251326
Ok(t, err)
@@ -1346,6 +1347,7 @@ func setupE2E(t *testing.T, repoDir string, opt setupOption) (events_controllers
13461347
}
13471348
}
13481349

1350+
defaultTFDistribution := terraformClient.DefaultDistribution()
13491351
defaultTFVersion := terraformClient.DefaultVersion()
13501352
locker := events.NewDefaultWorkingDirLocker()
13511353
parser := &config.ParserValidator{}
@@ -1429,7 +1431,7 @@ func setupE2E(t *testing.T, repoDir string, opt setupOption) (events_controllers
14291431
terraformClient,
14301432
)
14311433

1432-
showStepRunner, err := runtime.NewShowStepRunner(terraformClient, defaultTFVersion)
1434+
showStepRunner, err := runtime.NewShowStepRunner(terraformClient, defaultTFDistribution, defaultTFVersion)
14331435

14341436
Ok(t, err)
14351437

@@ -1440,6 +1442,7 @@ func setupE2E(t *testing.T, repoDir string, opt setupOption) (events_controllers
14401442
conftextExec.VersionCache = &LocalConftestCache{}
14411443

14421444
policyCheckRunner, err := runtime.NewPolicyCheckStepRunner(
1445+
defaultTFDistribution,
14431446
defaultTFVersion,
14441447
conftextExec,
14451448
)
@@ -1451,11 +1454,13 @@ func setupE2E(t *testing.T, repoDir string, opt setupOption) (events_controllers
14511454
Locker: projectLocker,
14521455
LockURLGenerator: &mockLockURLGenerator{},
14531456
InitStepRunner: &runtime.InitStepRunner{
1454-
TerraformExecutor: terraformClient,
1455-
DefaultTFVersion: defaultTFVersion,
1457+
TerraformExecutor: terraformClient,
1458+
DefaultTFDistribution: defaultTFDistribution,
1459+
DefaultTFVersion: defaultTFVersion,
14561460
},
14571461
PlanStepRunner: runtime.NewPlanStepRunner(
14581462
terraformClient,
1463+
defaultTFDistribution,
14591464
defaultTFVersion,
14601465
statusUpdater,
14611466
asyncTfExec,
@@ -1465,10 +1470,11 @@ func setupE2E(t *testing.T, repoDir string, opt setupOption) (events_controllers
14651470
ApplyStepRunner: &runtime.ApplyStepRunner{
14661471
TerraformExecutor: terraformClient,
14671472
},
1468-
ImportStepRunner: runtime.NewImportStepRunner(terraformClient, defaultTFVersion),
1469-
StateRmStepRunner: runtime.NewStateRmStepRunner(terraformClient, defaultTFVersion),
1473+
ImportStepRunner: runtime.NewImportStepRunner(terraformClient, defaultTFDistribution, defaultTFVersion),
1474+
StateRmStepRunner: runtime.NewStateRmStepRunner(terraformClient, defaultTFDistribution, defaultTFVersion),
14701475
RunStepRunner: &runtime.RunStepRunner{
14711476
TerraformExecutor: terraformClient,
1477+
DefaultTFDistribution: defaultTFDistribution,
14721478
DefaultTFVersion: defaultTFVersion,
14731479
ProjectCmdOutputHandler: projectCmdOutputHandler,
14741480
},

Diff for: server/core/config/parser_validator_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,31 @@ workflows:
610610
},
611611
},
612612
},
613+
{
614+
description: "project field with terraform_distribution set to opentofu",
615+
input: `
616+
version: 3
617+
projects:
618+
- dir: .
619+
workspace: myworkspace
620+
terraform_distribution: opentofu
621+
`,
622+
exp: valid.RepoCfg{
623+
Version: 3,
624+
Projects: []valid.Project{
625+
{
626+
Dir: ".",
627+
Workspace: "myworkspace",
628+
TerraformDistribution: String("opentofu"),
629+
Autoplan: valid.Autoplan{
630+
WhenModified: raw.DefaultAutoPlanWhenModified,
631+
Enabled: true,
632+
},
633+
},
634+
},
635+
Workflows: make(map[string]valid.Workflow),
636+
},
637+
},
613638
{
614639
description: "project dir with ..",
615640
input: `

Diff for: server/core/config/raw/project.go

+13
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ type Project struct {
2626
Dir *string `yaml:"dir,omitempty"`
2727
Workspace *string `yaml:"workspace,omitempty"`
2828
Workflow *string `yaml:"workflow,omitempty"`
29+
TerraformDistribution *string `yaml:"terraform_distribution,omitempty"`
2930
TerraformVersion *string `yaml:"terraform_version,omitempty"`
3031
Autoplan *Autoplan `yaml:"autoplan,omitempty"`
3132
PlanRequirements []string `yaml:"plan_requirements,omitempty"`
@@ -86,6 +87,7 @@ func (p Project) Validate() error {
8687
validation.Field(&p.PlanRequirements, validation.By(validPlanReq)),
8788
validation.Field(&p.ApplyRequirements, validation.By(validApplyReq)),
8889
validation.Field(&p.ImportRequirements, validation.By(validImportReq)),
90+
validation.Field(&p.TerraformDistribution, validation.By(validDistribution)),
8991
validation.Field(&p.TerraformVersion, validation.By(VersionValidator)),
9092
validation.Field(&p.DependsOn, validation.By(DependsOn)),
9193
validation.Field(&p.Name, validation.By(validName)),
@@ -118,6 +120,9 @@ func (p Project) ToValid() valid.Project {
118120
if p.TerraformVersion != nil {
119121
v.TerraformVersion, _ = version.NewVersion(*p.TerraformVersion)
120122
}
123+
if p.TerraformDistribution != nil {
124+
v.TerraformDistribution = p.TerraformDistribution
125+
}
121126
if p.Autoplan == nil {
122127
v.Autoplan = DefaultAutoPlan()
123128
} else {
@@ -202,3 +207,11 @@ func validImportReq(value interface{}) error {
202207
}
203208
return nil
204209
}
210+
211+
func validDistribution(value interface{}) error {
212+
distribution := value.(*string)
213+
if distribution != nil && *distribution != "terraform" && *distribution != "opentofu" {
214+
return fmt.Errorf("'%s' is not a valid terraform_distribution, only '%s' and '%s' are supported", *distribution, "terraform", "opentofu")
215+
}
216+
return nil
217+
}

Diff for: server/core/config/valid/global_cfg.go

+3
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ type MergedProjectCfg struct {
105105
AutoplanEnabled bool
106106
AutoMergeDisabled bool
107107
AutoMergeMethod string
108+
TerraformDistribution *string
108109
TerraformVersion *version.Version
109110
RepoCfgVersion int
110111
PolicySets PolicySets
@@ -412,6 +413,7 @@ func (g GlobalCfg) MergeProjectCfg(log logging.SimpleLogging, repoID string, pro
412413
DependsOn: proj.DependsOn,
413414
Name: proj.GetName(),
414415
AutoplanEnabled: proj.Autoplan.Enabled,
416+
TerraformDistribution: proj.TerraformDistribution,
415417
TerraformVersion: proj.TerraformVersion,
416418
RepoCfgVersion: rCfg.Version,
417419
PolicySets: g.PolicySets,
@@ -438,6 +440,7 @@ func (g GlobalCfg) DefaultProjCfg(log logging.SimpleLogging, repoID string, repo
438440
Workspace: workspace,
439441
Name: "",
440442
AutoplanEnabled: DefaultAutoPlanEnabled,
443+
TerraformDistribution: nil,
441444
TerraformVersion: nil,
442445
PolicySets: g.PolicySets,
443446
DeleteSourceBranchOnMerge: deleteSourceBranchOnMerge,

Diff for: server/core/config/valid/repo_cfg.go

+1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ type Project struct {
147147
Workspace string
148148
Name *string
149149
WorkflowName *string
150+
TerraformDistribution *string
150151
TerraformVersion *version.Version
151152
Autoplan Autoplan
152153
PlanRequirements []string

0 commit comments

Comments
 (0)