Skip to content

Commit

Permalink
Merge pull request #171 from Cox-Automotive/byo-trust-policy
Browse files Browse the repository at this point in the history
Byo trust policy
  • Loading branch information
americk0 authored Jun 15, 2022
2 parents 03ffb92 + 5b21cb2 commit 75aed66
Show file tree
Hide file tree
Showing 9 changed files with 245 additions and 37 deletions.
41 changes: 40 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,40 @@ provider "alks" {
}
```

### Tags
You can specify tags to add to all of your roles created with ALKS by using the `default_tags` block in the provider configuration. You can also choose to ignore existing tags on a resource by including tag keys or key prefixes in the `ignore_tags` block. These ignored tags will not show up on Terraform Plans or Applys, and will not be removed from the resource by Terraform.

You may also specify tags on individual roles using the `tags` block.

Your ALKS configuration could look like this:

```hcl
provider "alks" {
url = "https://alks.foo.com/rest"
version = ">= 2.3.0"
default_tags {
tags = {
"defaultTagKey" = "defaultTagValue"
}
}
ignore_tags {
keys = ["ignoreThisKey"]
key_prefixes = ["cai:", "coxauto:"]
}
}
resource "alks_iamrole" "test_role" {
name = "My_Test_Role"
type = "Amazon EC2"
include_default_policies = false
enable_alks_access = false
tags = {
"roleSpecificTagKey" = "value"
}
}
```

Note: Role specific tag values will overwrite default values if the key appears in both places.


### Multiple Provider Configuration

Expand Down Expand Up @@ -147,7 +181,7 @@ resource "alks_iamrole" "test_role_nonprod" {

## Argument Reference

In addition to [generic `provider` arguments](https://www.terraform.io/docs/configuration/providers.html?_ga=2.182283811.562816692.1597670778-20010454.1565803281) (e.g. `alias` and `version`), the following arguments are supported in the AWS provider block:
In addition to [generic `provider` arguments](https://www.terraform.io/docs/configuration/providers.html?_ga=2.182283811.562816692.1597670778-20010454.1565803281) (e.g. `alias` and `version`), the following arguments are supported in the ALKS provider block:

* `url` - (Required) The URL to your ALKS server. Also read from ENV.ALKS_URL
* `access_key` - (Optional) The access key from a valid STS session. Also read from ENV.ALKS_ACCESS_KEY_ID and ENV.AWS_ACCESS_KEY_ID.
Expand All @@ -160,6 +194,11 @@ In addition to [generic `provider` arguments](https://www.terraform.io/docs/conf
* `session_name` - (Optional) The session name to provide to AWS when creating STS credentials. Please see the AWS SDK documentation for more information.
* `external_id` - (Optional) The external identifier to provide to AWS when creating STS credentials. Please see the AWS SDK documentation for more information.
* `policy` - (Optional) This specifies additional policy restrictions to apply to the resulting STS credentials beyond any existing inline or managed policies. Please see the AWS SDK documentation for more information.
* `default_tags` - (Optional) This block can hold a block of tags to add to all roles created by this provider
* `tags` - (Optional) Block of key value pairs to add to all roles
* `ignore_tags` - (Optional) Can contain a list of tag keys or key prefixes to exclude from `terraform plan` and `terraform apply`. This is for tags added outside of the alks provider that are managed externally
* `keys` - (Optional) List of keys to ignore
* `key_prefixes` - (Optional) List of key prefixes to ignore. Any key starting with a string in this list will be ignored.

---
### Supported Versions
Expand Down
44 changes: 42 additions & 2 deletions docs/resources/alks_iamrole.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,41 @@ Creates an custom ALKS IAM role for usage in an AWS account.

### ALKS IAM Role Creation

#### IAM Role with a custom trust policy document

```hcl
resource "alks_iamrole" "test_role" {
name = "My_Test_Role"
type = "Amazon EC2"
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Action = "sts:AssumeRole",
Effect = "Allow",
Principal = {
Service = "ec2.amazonaws.com"
},
Sid = ""
}
]
})
include_default_policies = false
enable_alks_access = false
}
```

This will create a role with the exact name `My_Test_Role`.
This will create a role with the exact name `My_Test_Role`. Specifying a custom trust policy like this is currently only supported for single-service trust policies trusting an approved AWS service, and at the moment no extra fields may be provided such as the "Condition" or "Resource" keys. At this time, the only acceptable changes to the JSON string passed to the assume_role_policy field above are that `ec2.amazonaws.com` can be swapped out for any single approved service, and the `Sid` field may be omitted or populated with any valid Sid according to AWS's documentation.

#### IAM Role specifying a role type

```hcl
resource "alks_iamrole" "test_role" {
name = "My_Test_Role"
type = "Amazon EC2"
include_default_policies = false
enable_alks_access = false
}
```

### ALKS IAM Role Creation with Name Prefix

Expand Down Expand Up @@ -47,6 +72,20 @@ resource "alks_iamrole" "test_dynamic_role" {
}
```

### ALKS IAM Role Creation With Tags

```hcl
resource "alks_iamrole" "test_role" {
name = "My_Test_Role"
type = "Amazon EC2"
include_default_policies = false
enable_alks_access = false
tags = {
"tagKey" = "tagValue"
}
}
```

## Argument Reference

The following arguments are supported:
Expand All @@ -60,6 +99,7 @@ The following arguments are supported:
* `ip_arn` - (Computed) If `role_added_to_ip` was `true` this will provide the ARN of the instance profile role.
* `enable_alks_access` - (Optional) If `true`, allows ALKS calls to be made by instance profiles or Lambda functions making use of this role. Note: This enables **machine identity** capability.
* `template_fields` - (Optional) If present, will submit template field data to ALKS. Note: This will generate an error if the role type does not support template fields.
* `tags` - (Optional) If present, will add specified tags onto role.

## Import

Expand Down
16 changes: 16 additions & 0 deletions docs/resources/alks_iamtrustrole.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ resource "alks_iamtrustrole" "test_trust_role" {
}
```

### ALKS IAM Role Creation With Tags

```hcl
resource "alks_iamrole" "test_role" {
name = "My_Test_Role"
type = "Amazon EC2"
include_default_policies = false
enable_alks_access = false
tags = {
"tagKey" = "tagValue"
}
}
```

## Argument Reference

The following arguments are supported:
Expand All @@ -28,6 +42,8 @@ The following arguments are supported:
* `arn` - (Computed) Provides the ARN of the role that was created.
* `ip_arn` - (Computed) If `role_added_to_ip` was `true` this will provide the ARN of the instance profile role.
* `enable_alks_access` - (Optional) If `true`, allows ALKS calls to be made by instance profiles or Lambda functions making use of this role. Note: This enables **machine identity** capability.
* `tags` - (Optional) If present, will add specified tags onto role.


## Import

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/Cox-Automotive/terraform-provider-alks
go 1.14

require (
github.com/Cox-Automotive/alks-go v0.0.0-20220502192728-623c28f3b92b
github.com/Cox-Automotive/alks-go v0.0.0-20220610194553-5bc77030a1ba
github.com/aws/aws-sdk-go v1.31.15
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/terraform-json v0.13.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/Cox-Automotive/alks-go v0.0.0-20220502192728-623c28f3b92b h1:lTQ/h4MVJzOmrWk0a16zb9pUapImXFeTlQkO3vlZtUI=
github.com/Cox-Automotive/alks-go v0.0.0-20220502192728-623c28f3b92b/go.mod h1:jJNgXthl59Vt2tJHSC3WZ0vlopV9xqdclfQuLgwHjOw=
github.com/Cox-Automotive/alks-go v0.0.0-20220610194553-5bc77030a1ba h1:2a3ugAGVFcRPYNNeO3DVHlFDjhoWIgwOCOG+YTDaqaU=
github.com/Cox-Automotive/alks-go v0.0.0-20220610194553-5bc77030a1ba/go.mod h1:jJNgXthl59Vt2tJHSC3WZ0vlopV9xqdclfQuLgwHjOw=
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE=
github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
Expand Down
29 changes: 24 additions & 5 deletions resource_alks_iamrole.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"encoding/json"
"fmt"
"log"

Expand Down Expand Up @@ -40,9 +41,16 @@ func resourceAlksIamRole() *schema.Resource {
ValidateFunc: ValidRolePrefix,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ExactlyOneOf: []string{"assume_role_policy", "type"},
},
"assume_role_policy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ExactlyOneOf: []string{"assume_role_policy", "type"},
},
"include_default_policies": {
Type: schema.TypeBool,
Expand Down Expand Up @@ -87,7 +95,6 @@ func resourceAlksIamRole() *schema.Resource {
func resourceAlksIamRoleCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[INFO] ALKS IAM Role Create")
var roleName = NameWithPrefix(d.Get("name").(string), d.Get("name_prefix").(string))
var roleType = d.Get("type").(string)
var incDefPol = d.Get("include_default_policies").(bool)
var enableAlksAccess = d.Get("enable_alks_access").(bool)
var rawTemplateFields = d.Get("template_fields").(map[string]interface{})
Expand Down Expand Up @@ -116,14 +123,26 @@ func resourceAlksIamRoleCreate(ctx context.Context, d *schema.ResourceData, meta

options := &alks.CreateIamRoleOptions{
RoleName: &roleName,
RoleType: &roleType,
IncludeDefaultPolicies: &include,
AlksAccess: &enableAlksAccess,
TemplateFields: &templateFields,
MaxSessionDurationInSeconds: &maxSessionDurationInSeconds,
Tags: &allTags,
}

if roleType, ok := d.GetOk("type"); ok {
roleTypeString := roleType.(string)
options.RoleType = &roleTypeString
} else {
trustPolicyString := d.Get("assume_role_policy").(string)

trustPolicy := new(map[string]interface{})

json.Unmarshal([]byte(trustPolicyString), trustPolicy)

options.TrustPolicy = trustPolicy
}

resp, err := client.CreateIamRole(options)
if err != nil {
return diag.FromErr(err)
Expand Down
78 changes: 78 additions & 0 deletions resource_alks_iamrole_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,43 @@ func testAccCheckAlksIamRoleAttributes(role *alks.IamRoleResponse) resource.Test
}
}

func TestIAMRole_RoleTypeAndTrustPolicyBothPresent(t *testing.T) {
var resp alks.IamRoleResponse

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAlksIamRoleDestroy(&resp),
Steps: []resource.TestStep{
{
Config: testAccCheckAlksIamRoleBothRoleTypeAndTrustPolicyPresent,
ExpectError: regexp.MustCompile(".*Error: ExactlyOne.*"),
},
},
})
}

func TestIAMRole_OnlyTrustPolicyPresent(t *testing.T) {
var resp alks.IamRoleResponse

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAlksIamRoleDestroy(&resp),
Steps: []resource.TestStep{
{
Config: testAccCheckAlksIamRoleWithOnlyTrustPolicyPresent,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"alks_iamrole.both_type_and_trust_policy", "name", "both_type_and_trust_policy"),
resource.TestCheckResourceAttr(
"alks_iamrole.both_type_and_trust_policy", "include_default_policies", "false"),
),
},
},
})
}

const testAccCheckAlksIamRoleConfigBasic = `
resource "alks_iamrole" "foo" {
name = "bar430"
Expand Down Expand Up @@ -643,3 +680,44 @@ const testAccCheckAlksIamRoleConfigNameTooLong = `
include_default_policies = false
}
`

const testAccCheckAlksIamRoleBothRoleTypeAndTrustPolicyPresent = `
resource "alks_iamrole" "both_type_and_trust_policy" {
name = "both_type_and_trust_policy"
include_default_policies = false
type = "Amazon EC2"
trust_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Action = "sts:AssumeRole",
Effect = "Allow",
Principal = {
Service = "databrew.amazonaws.com"
},
Sid = ""
}
]
})
}
`

const testAccCheckAlksIamRoleWithOnlyTrustPolicyPresent = `
resource "alks_iamrole" "both_type_and_trust_policy" {
name = "both_type_and_trust_policy"
include_default_policies = false
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Action = "sts:AssumeRole",
Effect = "Allow",
Principal = {
Service = "databrew.amazonaws.com"
},
Sid = ""
}
]
})
}
`
Loading

0 comments on commit 75aed66

Please sign in to comment.