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

r/iam_virtual_mfa_device - new resource #23113

Merged
merged 9 commits into from
Feb 11, 2022
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 .changelog/23113.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-data-source
aws_iam_virtual_mfa_device
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1407,6 +1407,7 @@ func Provider() *schema.Provider {
"aws_iam_user_policy": iam.ResourceUserPolicy(),
"aws_iam_user_policy_attachment": iam.ResourceUserPolicyAttachment(),
"aws_iam_user_ssh_key": iam.ResourceUserSSHKey(),
"aws_iam_virtual_mfa_device": iam.ResourceVirtualMfaDevice(),

"aws_imagebuilder_component": imagebuilder.ResourceComponent(),
"aws_imagebuilder_distribution_configuration": imagebuilder.ResourceDistributionConfiguration(),
Expand Down
29 changes: 29 additions & 0 deletions internal/service/iam/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,32 @@ func FindRoleByName(conn *iam.IAM, name string) (*iam.Role, error) {

return output.Role, nil
}

func FindVirtualMfaDevice(conn *iam.IAM, serialNum string) (*iam.VirtualMFADevice, error) {
input := &iam.ListVirtualMFADevicesInput{}

output, err := conn.ListVirtualMFADevices(input)

if err != nil {
return nil, err
}

if len(output.VirtualMFADevices) == 0 || output.VirtualMFADevices[0] == nil {
return nil, tfresource.NewEmptyResultError(output)
}

var device *iam.VirtualMFADevice

for _, dvs := range output.VirtualMFADevices {
if aws.StringValue(dvs.SerialNumber) == serialNum {
device = dvs
break
}
}

if device == nil {
return nil, tfresource.NewEmptyResultError(device)
}

return device, nil
}
56 changes: 56 additions & 0 deletions internal/service/iam/sweep.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ func init() {
resource.AddTestSweepers("aws_iam_user", &resource.Sweeper{
Name: "aws_iam_user",
F: sweepUsers,
Dependencies: []string{
"aws_iam_virtual_mfa_device",
},
})

resource.AddTestSweepers("aws_iam_virtual_mfa_device", &resource.Sweeper{
Name: "aws_iam_virtual_mfa_device",
F: sweepVirtualMfaDevice,
})
}

Expand Down Expand Up @@ -782,3 +790,51 @@ func roleNameFilter(name string) bool {

return false
}

func sweepVirtualMfaDevice(region string) error {
client, err := sweep.SharedRegionalSweepClient(region)
if err != nil {
return fmt.Errorf("error getting client: %s", err)
}
conn := client.(*conns.AWSClient).IAMConn
var sweeperErrs *multierror.Error
input := &iam.ListVirtualMFADevicesInput{}

err = conn.ListVirtualMFADevicesPages(input, func(page *iam.ListVirtualMFADevicesOutput, lastPage bool) bool {
if len(page.VirtualMFADevices) == 0 {
log.Printf("[INFO] No IAM Virtual MFA Devices to sweep")
return true
}
for _, device := range page.VirtualMFADevices {
serialNum := aws.StringValue(device.SerialNumber)

if strings.Contains(serialNum, "root-account-mfa-device") {
log.Printf("[INFO] Skipping IAM Root Virtual MFA Device: %s", device)
continue
}

r := ResourceVirtualMfaDevice()
d := r.Data(nil)
d.SetId(serialNum)
err := r.Delete(d, client)
if err != nil {
sweeperErr := fmt.Errorf("error deleting IAM Virtual MFA Device (%s): %w", device, err)
log.Printf("[ERROR] %s", sweeperErr)
sweeperErrs = multierror.Append(sweeperErrs, sweeperErr)
continue
}
}
return !lastPage
})

if sweep.SkipSweepError(err) {
log.Printf("[WARN] Skipping IAM Virtual MFA Device sweep for %s: %s", region, err)
return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors
}

if err != nil {
sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error describing IAM Virtual MFA Devices: %w", err))
}

return sweeperErrs.ErrorOrNil()
}
35 changes: 35 additions & 0 deletions internal/service/iam/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,38 @@ func serverCertificateUpdateTags(conn *iam.IAM, identifier string, oldTagsMap in

return nil
}

// virtualMfaUpdateTags updates IAM Virtual MFA Device tags.
// The identifier is the Virtual MFA Device ARN.
func virtualMfaUpdateTags(conn *iam.IAM, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error {
oldTags := tftags.New(oldTagsMap)
newTags := tftags.New(newTagsMap)

if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 {
input := &iam.UntagMFADeviceInput{
SerialNumber: aws.String(identifier),
TagKeys: aws.StringSlice(removedTags.Keys()),
}

_, err := conn.UntagMFADevice(input)

if err != nil {
return fmt.Errorf("error untagging resource (%s): %w", identifier, err)
}
}

if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 {
input := &iam.TagMFADeviceInput{
SerialNumber: aws.String(identifier),
Tags: Tags(updatedTags.IgnoreAWS()),
}

_, err := conn.TagMFADevice(input)

if err != nil {
return fmt.Errorf("error tagging resource (%s): %w", identifier, err)
}
}

return nil
}
162 changes: 162 additions & 0 deletions internal/service/iam/virtual_mfa_device.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package iam

import (
"fmt"
"log"
"regexp"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)

func ResourceVirtualMfaDevice() *schema.Resource {
return &schema.Resource{
Create: resourceVirtualMfaDeviceCreate,
Read: resourceVirtualMfaDeviceRead,
Update: resourceVirtualMfaDeviceUpdate,
Delete: resourceVirtualMfaDeviceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"base_32_string_seed": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeString,
Optional: true,
Default: "/",
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 512),
},
"qr_code_png": {
Type: schema.TypeString,
Computed: true,
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
"virtual_mfa_device_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(
regexp.MustCompile(`[\w+=,.@-]+`),
"must consist of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: _+=,.@-",
),
},
},
CustomizeDiff: verify.SetTagsDiff,
}
}

func resourceVirtualMfaDeviceCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).IAMConn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{})))

name := d.Get("virtual_mfa_device_name").(string)
request := &iam.CreateVirtualMFADeviceInput{
Path: aws.String(d.Get("path").(string)),
VirtualMFADeviceName: aws.String(name),
}

if len(tags) > 0 {
request.Tags = Tags(tags.IgnoreAWS())
}

output, err := conn.CreateVirtualMFADevice(request)
if err != nil {
return fmt.Errorf("Error creating IAM Virtual MFA Device %s: %w", name, err)
}
vMfa := output.VirtualMFADevice
d.SetId(aws.StringValue(vMfa.SerialNumber))

d.Set("base_32_string_seed", string(vMfa.Base32StringSeed))
d.Set("qr_code_png", string(vMfa.QRCodePNG))

return resourceVirtualMfaDeviceRead(d, meta)
}

func resourceVirtualMfaDeviceRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).IAMConn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig

output, err := FindVirtualMfaDevice(conn, d.Id())

if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] IAM Virtual MFA Device (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

if err != nil {
return fmt.Errorf("error reading IAM Virtual MFA Device (%s): %w", d.Id(), err)
}

d.Set("arn", output.SerialNumber)

// The call above returns empty tags
tagsInput := &iam.ListMFADeviceTagsInput{
SerialNumber: aws.String(d.Id()),
}

mfaTags, err := conn.ListMFADeviceTags(tagsInput)
if err != nil {
return fmt.Errorf("error listing IAM Virtual MFA Device Tags (%s): %w", d.Id(), err)
}

tags := KeyValueTags(mfaTags.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig)

//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return fmt.Errorf("error setting tags: %w", err)
}

if err := d.Set("tags_all", tags.Map()); err != nil {
return fmt.Errorf("error setting tags_all: %w", err)
}

return nil
}

func resourceVirtualMfaDeviceUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).IAMConn

o, n := d.GetChange("tags_all")

if err := virtualMfaUpdateTags(conn, d.Id(), o, n); err != nil {
return fmt.Errorf("error updating tags for IAM Virtual MFA Device (%s): %w", d.Id(), err)
}

return resourceVirtualMfaDeviceRead(d, meta)
}

func resourceVirtualMfaDeviceDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).IAMConn

request := &iam.DeleteVirtualMFADeviceInput{
SerialNumber: aws.String(d.Id()),
}

if _, err := conn.DeleteVirtualMFADevice(request); err != nil {
if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) {
return nil
}
return fmt.Errorf("Error deleting IAM Virtual MFA Device %s: %w", d.Id(), err)
}
return nil
}
Loading