Skip to content

Commit

Permalink
Set a version to attribute value only if the key exists
Browse files Browse the repository at this point in the history
  • Loading branch information
minamijoyo committed Sep 4, 2019
1 parent bd9fb4b commit 0a1264c
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 3 deletions.
11 changes: 9 additions & 2 deletions tfupdate/provider.go
Expand Up @@ -52,7 +52,11 @@ func (u *ProviderUpdater) updateTerraformBlock(f *hclwrite.File) error {
if p == nil {
return nil
}
p.Body().SetAttributeValue(u.name, cty.StringVal(u.version))

// set a version to attribute value only if the key exists
if p.Body().GetAttribute(u.name) != nil {
p.Body().SetAttributeValue(u.name, cty.StringVal(u.version))
}

return nil
}
Expand All @@ -63,7 +67,10 @@ func (u *ProviderUpdater) updateProviderBlock(f *hclwrite.File) error {
return nil
}

p.Body().SetAttributeValue("version", cty.StringVal(u.version))
// set a version to attribute value only if the key exists
if p.Body().GetAttribute("version") != nil {
p.Body().SetAttributeValue("version", cty.StringVal(u.version))
}

return nil
}
36 changes: 36 additions & 0 deletions tfupdate/provider_test.go
Expand Up @@ -97,6 +97,42 @@ provider "aws" {
version = "2.23.0"
region = "ap-northeast-1"
}
`,
ok: true,
},
{
src: `
terraform {
required_version = "0.12.4"
required_providers {
null = "2.1.1"
}
}
`,
name: "aws",
version: "2.23.0",
want: `
terraform {
required_version = "0.12.4"
required_providers {
null = "2.1.1"
}
}
`,
ok: true,
},
{
src: `
provider "aws" {
region = "ap-northeast-1"
}
`,
name: "aws",
version: "2.23.0",
want: `
provider "aws" {
region = "ap-northeast-1"
}
`,
ok: true,
},
Expand Down
9 changes: 8 additions & 1 deletion tfupdate/terraform.go
Expand Up @@ -26,7 +26,14 @@ func NewTerraformUpdater(version string) (Updater, error) {
// Note that this method will rewrite the AST passed as an argument.
func (u *TerraformUpdater) Update(f *hclwrite.File) error {
tf := f.Body().FirstMatchingBlock("terraform", []string{})
tf.Body().SetAttributeValue("required_version", cty.StringVal(u.version))
if tf == nil {
return nil
}

// set a version to attribute value only if the key exists
if tf.Body().GetAttribute("required_version") != nil {
tf.Body().SetAttributeValue("required_version", cty.StringVal(u.version))
}

return nil
}
34 changes: 34 additions & 0 deletions tfupdate/terraform_test.go
Expand Up @@ -62,6 +62,40 @@ terraform {
terraform {
required_version = "0.12.7"
}
`,
ok: true,
},
{
src: `
terraform {
required_providers {
null = "2.1.1"
}
}
`,
version: "0.12.7",
want: `
terraform {
required_providers {
null = "2.1.1"
}
}
`,
ok: true,
},
{
src: `
provider "aws" {
version = "2.11.0"
region = "ap-northeast-1"
}
`,
version: "0.12.7",
want: `
provider "aws" {
version = "2.11.0"
region = "ap-northeast-1"
}
`,
ok: true,
},
Expand Down

0 comments on commit 0a1264c

Please sign in to comment.