|
1 | 1 | package aws
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
4 | 5 | "log"
|
5 | 6 |
|
6 | 7 | "github.com/aws/aws-sdk-go/aws"
|
@@ -75,6 +76,10 @@ func resourceAwsIotPolicyRead(d *schema.ResourceData, meta interface{}) error {
|
75 | 76 | func resourceAwsIotPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
|
76 | 77 | conn := meta.(*AWSClient).iotconn
|
77 | 78 |
|
| 79 | + if err := iotPolicyPruneVersions(d.Id(), conn); err != nil { |
| 80 | + return err |
| 81 | + } |
| 82 | + |
78 | 83 | if d.HasChange("policy") {
|
79 | 84 | _, err := conn.CreatePolicyVersion(&iot.CreatePolicyVersionInput{
|
80 | 85 | PolicyName: aws.String(d.Id()),
|
@@ -129,3 +134,55 @@ func resourceAwsIotPolicyDelete(d *schema.ResourceData, meta interface{}) error
|
129 | 134 |
|
130 | 135 | return nil
|
131 | 136 | }
|
| 137 | + |
| 138 | +// iotPolicyPruneVersions deletes the oldest non-default version if the maximum |
| 139 | +// number of versions (5) has been reached. |
| 140 | +func iotPolicyPruneVersions(name string, iotconn *iot.IoT) error { |
| 141 | + versions, err := iotPolicyListVersions(name, iotconn) |
| 142 | + if err != nil { |
| 143 | + return err |
| 144 | + } |
| 145 | + if len(versions) < 5 { |
| 146 | + return nil |
| 147 | + } |
| 148 | + |
| 149 | + var oldestVersion *iot.PolicyVersion |
| 150 | + |
| 151 | + for _, version := range versions { |
| 152 | + if *version.IsDefaultVersion { |
| 153 | + continue |
| 154 | + } |
| 155 | + if oldestVersion == nil || |
| 156 | + version.CreateDate.Before(*oldestVersion.CreateDate) { |
| 157 | + oldestVersion = version |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + err = iotPolicyDeleteVersion(name, *oldestVersion.VersionId, iotconn) |
| 162 | + return err |
| 163 | +} |
| 164 | + |
| 165 | +func iotPolicyListVersions(name string, iotconn *iot.IoT) ([]*iot.PolicyVersion, error) { |
| 166 | + request := &iot.ListPolicyVersionsInput{ |
| 167 | + PolicyName: aws.String(name), |
| 168 | + } |
| 169 | + |
| 170 | + response, err := iotconn.ListPolicyVersions(request) |
| 171 | + if err != nil { |
| 172 | + return nil, fmt.Errorf("Error listing versions for IoT policy %s: %s", name, err) |
| 173 | + } |
| 174 | + return response.PolicyVersions, nil |
| 175 | +} |
| 176 | + |
| 177 | +func iotPolicyDeleteVersion(name, versionID string, iotconn *iot.IoT) error { |
| 178 | + request := &iot.DeletePolicyVersionInput{ |
| 179 | + PolicyName: aws.String(name), |
| 180 | + PolicyVersionId: aws.String(versionID), |
| 181 | + } |
| 182 | + |
| 183 | + _, err := iotconn.DeletePolicyVersion(request) |
| 184 | + if err != nil { |
| 185 | + return fmt.Errorf("Error deleting version %s from IoT policy %s: %s", versionID, name, err) |
| 186 | + } |
| 187 | + return nil |
| 188 | +} |
0 commit comments