Skip to content

Commit

Permalink
Merge pull request #2890 from devonbleak/f-iam-policy-source-json
Browse files Browse the repository at this point in the history
data-source/aws_iam_policy_document: Support layering via source_json and override_json attributes
  • Loading branch information
bflad committed Feb 5, 2018
2 parents 251ee29 + 91862d2 commit 97c6975
Show file tree
Hide file tree
Showing 4 changed files with 547 additions and 3 deletions.
39 changes: 36 additions & 3 deletions aws/data_source_aws_iam_policy_document.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,18 @@ func dataSourceAwsIamPolicyDocument() *schema.Resource {
Read: dataSourceAwsIamPolicyDocumentRead,

Schema: map[string]*schema.Schema{
"override_json": {
Type: schema.TypeString,
Optional: true,
},
"policy_id": {
Type: schema.TypeString,
Optional: true,
},
"source_json": {
Type: schema.TypeString,
Optional: true,
},
"statement": {
Type: schema.TypeList,
Required: true,
Expand Down Expand Up @@ -94,17 +102,22 @@ func dataSourceAwsIamPolicyDocument() *schema.Resource {
}

func dataSourceAwsIamPolicyDocumentRead(d *schema.ResourceData, meta interface{}) error {
doc := &IAMPolicyDoc{
Version: "2012-10-17",
doc := &IAMPolicyDoc{}

if sourceJson, hasSourceJson := d.GetOk("source_json"); hasSourceJson {
if err := json.Unmarshal([]byte(sourceJson.(string)), doc); err != nil {
return err
}
}

doc.Version = "2012-10-17"

if policyId, hasPolicyId := d.GetOk("policy_id"); hasPolicyId {
doc.Id = policyId.(string)
}

var cfgStmts = d.Get("statement").([]interface{})
stmts := make([]*IAMPolicyStatement, len(cfgStmts))
doc.Statements = stmts
for i, stmtI := range cfgStmts {
cfgStmt := stmtI.(map[string]interface{})
stmt := &IAMPolicyStatement{
Expand Down Expand Up @@ -148,6 +161,26 @@ func dataSourceAwsIamPolicyDocumentRead(d *schema.ResourceData, meta interface{}
stmts[i] = stmt
}

doc.Statements = append(doc.Statements, stmts...)

// merge in our override_json
if overrideJson, hasOverrideJson := d.GetOk("override_json"); hasOverrideJson {
overrideDoc := &IAMPolicyDoc{}
if err := json.Unmarshal([]byte(overrideJson.(string)), overrideDoc); err != nil {
return err
}

if len(overrideDoc.Id) > 0 {
doc.Id = overrideDoc.Id
}

if len(overrideDoc.Statements) > 0 {
doc.Statements = append(doc.Statements, overrideDoc.Statements...)
}
}

doc.DeDupSids()

jsonDoc, err := json.MarshalIndent(doc, "", " ")
if err != nil {
// should never happen if the above code is correct
Expand Down
Loading

0 comments on commit 97c6975

Please sign in to comment.