Skip to content
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

Added 3 checks for AWS Launch Configuration #318

Merged
merged 6 commits into from
Jun 7, 2019
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
3 changes: 3 additions & 0 deletions docs/rules/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,9 @@ The following table shows the correspondence between resources and rules. Rules
||aws_instance_invalid_vpc_security_group|✔|
|`aws_key_pair`|||
|`aws_launch_configuration`|||
||aws_launch_configuration_invalid_iam_profile|✔|
||aws_launch_configuration_invalid_image_id|✔|
||aws_launch_configuration_invalid_type||
|`aws_launch_template`|||
|`aws_placement_group`|||
|`aws_snapshot_create_volume_permission`|||
Expand Down
89 changes: 89 additions & 0 deletions rules/awsrules/aws_launch_configuration_invalid_iam_profile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package awsrules

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/hcl2/hcl"
"github.com/wata727/tflint/issue"
"github.com/wata727/tflint/tflint"
)

// AwsLaunchConfigurationInvalidIAMProfileRule checks whether profile actually exists
type AwsLaunchConfigurationInvalidIAMProfileRule struct {
resourceType string
attributeName string
profiles map[string]bool
dataPrepared bool
}

// NewAwsLaunchConfigurationInvalidIAMProfileRule returns new rule with default attributes
func NewAwsLaunchConfigurationInvalidIAMProfileRule() *AwsLaunchConfigurationInvalidIAMProfileRule {
return &AwsLaunchConfigurationInvalidIAMProfileRule{
resourceType: "aws_launch_configuration",
attributeName: "iam_instance_profile",
profiles: map[string]bool{},
dataPrepared: false,
}
}

// Name returns the rule name
func (r *AwsLaunchConfigurationInvalidIAMProfileRule) Name() string {
return "aws_launch_configuration_invalid_iam_profile"
}

// Enabled returns whether the rule is enabled by default
func (r *AwsLaunchConfigurationInvalidIAMProfileRule) Enabled() bool {
return true
}

// Type returns the rule severity
func (r *AwsLaunchConfigurationInvalidIAMProfileRule) Type() string {
return issue.ERROR
}

// Link returns the rule reference link
func (r *AwsLaunchConfigurationInvalidIAMProfileRule) Link() string {
return ""
}

// Check checks whether `iam_instance_profile` are included in the list retrieved by `ListInstanceProfiles`
func (r *AwsLaunchConfigurationInvalidIAMProfileRule) Check(runner *tflint.Runner) error {
log.Printf("[INFO] Check `%s` rule for `%s` runner", r.Name(), runner.TFConfigPath())

return runner.WalkResourceAttributes(r.resourceType, r.attributeName, func(attribute *hcl.Attribute) error {
if !r.dataPrepared {
log.Print("[DEBUG] Fetch instance profiles")
resp, err := runner.AwsClient.IAM.ListInstanceProfiles(&iam.ListInstanceProfilesInput{})
if err != nil {
err := &tflint.Error{
Code: tflint.ExternalAPIError,
Level: tflint.ErrorLevel,
Message: "An error occurred while describing launch configuration profiles",
Cause: err,
}
log.Printf("[ERROR] %s", err)
return err
}
for _, iamProfile := range resp.InstanceProfiles {
r.profiles[*iamProfile.InstanceProfileName] = true
}
r.dataPrepared = true
}

var profile string
err := runner.EvaluateExpr(attribute.Expr, &profile)

return runner.EnsureNoError(err, func() error {
if !r.profiles[profile] {
runner.EmitIssue(
r,
fmt.Sprintf("\"%s\" is invalid IAM profile name.", profile),
attribute.Expr.Range(),
)
}
return nil
})
})
}
129 changes: 129 additions & 0 deletions rules/awsrules/aws_launch_configuration_invalid_iam_profile_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package awsrules

import (
"io/ioutil"
"os"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/golang/mock/gomock"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform/configs"
"github.com/hashicorp/terraform/configs/configload"
"github.com/hashicorp/terraform/terraform"
"github.com/wata727/tflint/client"
"github.com/wata727/tflint/issue"
"github.com/wata727/tflint/tflint"
)

func Test_AwsLaunchConfigurationInvalidIAMProfile(t *testing.T) {
cases := []struct {
Name string
Content string
Response []*iam.InstanceProfile
Expected issue.Issues
}{
{
Name: "iam_instance_profile is invalid",
Content: `
resource "aws_launch_configuration" "web" {
iam_instance_profile = "app-server"
}`,
Response: []*iam.InstanceProfile{
{
InstanceProfileName: aws.String("app-server1"),
},
{
InstanceProfileName: aws.String("app-server2"),
},
},
Expected: []*issue.Issue{
{
Detector: "aws_launch_configuration_invalid_iam_profile",
Type: "ERROR",
Message: "\"app-server\" is invalid IAM profile name.",
Line: 3,
File: "resource.tf",
},
},
},
{
Name: "iam_instance_profile is valid",
Content: `
resource "aws_launch_configuration" "web" {
iam_instance_profile = "app-server"
}`,
Response: []*iam.InstanceProfile{
{
InstanceProfileName: aws.String("app-server1"),
},
{
InstanceProfileName: aws.String("app-server2"),
},
{
InstanceProfileName: aws.String("app-server"),
},
},
Expected: []*issue.Issue{},
},
}

dir, err := ioutil.TempDir("", "AwsLaunchConfigurationInvalidIamProfile")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)

currentDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(currentDir)

err = os.Chdir(dir)
if err != nil {
t.Fatal(err)
}

ctrl := gomock.NewController(t)
defer ctrl.Finish()

for _, tc := range cases {
loader, err := configload.NewLoader(&configload.Config{})
if err != nil {
t.Fatal(err)
}

err = ioutil.WriteFile(dir+"/resource.tf", []byte(tc.Content), os.ModePerm)
if err != nil {
t.Fatal(err)
}

mod, diags := loader.Parser().LoadConfigDir(".")
if diags.HasErrors() {
t.Fatal(diags)
}
cfg, tfdiags := configs.BuildConfig(mod, configs.DisabledModuleWalker)
if tfdiags.HasErrors() {
t.Fatal(tfdiags)
}

runner := tflint.NewRunner(tflint.EmptyConfig(), map[string]tflint.Annotations{}, cfg, map[string]*terraform.InputValue{})
rule := NewAwsLaunchConfigurationInvalidIAMProfileRule()

mock := client.NewMockIAMAPI(ctrl)
mock.EXPECT().ListInstanceProfiles(&iam.ListInstanceProfilesInput{}).Return(&iam.ListInstanceProfilesOutput{
InstanceProfiles: tc.Response,
}, nil)
runner.AwsClient.IAM = mock

if err = rule.Check(runner); err != nil {
t.Fatalf("Unexpected error occurred: %s", err)
}

if !cmp.Equal(tc.Expected, runner.Issues) {
t.Fatalf("Expected issues are not matched:\n %s\n", cmp.Diff(tc.Expected, runner.Issues))
}
}
}
90 changes: 90 additions & 0 deletions rules/awsrules/aws_launch_configuration_invalid_image_id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package awsrules

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/hcl2/hcl"
"github.com/wata727/tflint/issue"
"github.com/wata727/tflint/tflint"
)

// AwsLaunchConfigurationInvalidImageIDRule checks whether "aws_instance" has invalid AMI ID
type AwsLaunchConfigurationInvalidImageIDRule struct {
resourceType string
attributeName string
amiIDs map[string]bool
}

// NewAwsLaunchConfigurationInvalidImageIDRule returns new rule with default attributes
func NewAwsLaunchConfigurationInvalidImageIDRule() *AwsLaunchConfigurationInvalidImageIDRule {
return &AwsLaunchConfigurationInvalidImageIDRule{
resourceType: "aws_launch_configuration",
attributeName: "image_id",
amiIDs: map[string]bool{},
}
}

// Name returns the rule name
func (r *AwsLaunchConfigurationInvalidImageIDRule) Name() string {
return "aws_launch_configuration_invalid_image_id"
}

// Enabled returns whether the rule is enabled by default
func (r *AwsLaunchConfigurationInvalidImageIDRule) Enabled() bool {
return true
}

// Type returns the rule severity
func (r *AwsLaunchConfigurationInvalidImageIDRule) Type() string {
return issue.ERROR
}

// Link returns the rule reference link
func (r *AwsLaunchConfigurationInvalidImageIDRule) Link() string {
return ""
}

// Check checks whether "aws_instance" has invalid AMI ID
func (r *AwsLaunchConfigurationInvalidImageIDRule) Check(runner *tflint.Runner) error {
log.Printf("[INFO] Check `%s` rule for `%s` runner", r.Name(), runner.TFConfigPath())

return runner.WalkResourceAttributes(r.resourceType, r.attributeName, func(attribute *hcl.Attribute) error {
var ami string
err := runner.EvaluateExpr(attribute.Expr, &ami)

return runner.EnsureNoError(err, func() error {
if !r.amiIDs[ami] {
log.Printf("[DEBUG] Fetch AMI images: %s", ami)
resp, err := runner.AwsClient.EC2.DescribeImages(&ec2.DescribeImagesInput{
ImageIds: aws.StringSlice([]string{ami}),
})
if err != nil {
err := &tflint.Error{
Code: tflint.ExternalAPIError,
Level: tflint.ErrorLevel,
Message: "An error occurred while describing images",
Cause: err,
}
log.Printf("[ERROR] %s", err)
return err
}

if len(resp.Images) != 0 {
for _, image := range resp.Images {
r.amiIDs[*image.ImageId] = true
}
} else {
runner.EmitIssue(
r,
fmt.Sprintf("\"%s\" is invalid image ID.", ami),
attribute.Expr.Range(),
)
}
}
return nil
})
})
}
Loading