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

Add force destroy support for Transfer Server #6935

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
51 changes: 51 additions & 0 deletions aws/resource_aws_transfer_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ func resourceAwsTransferServer() *schema.Resource {
ValidateFunc: validateArn,
},

"force_destroy": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},

"tags": tagsSchema(),
},
}
Expand Down Expand Up @@ -194,6 +200,13 @@ func resourceAwsTransferServerUpdate(d *schema.ResourceData, meta interface{}) e
func resourceAwsTransferServerDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).transferconn

if d.Get("force_destroy").(bool) {
log.Printf("[DEBUG] Transfer Server (%s) attempting to forceDestroy", d.Id())
if err := deleteTransferUsers(conn, d.Id(), nil); err != nil {
return err
}
}

delOpts := &transfer.DeleteServerInput{
ServerId: aws.String(d.Id()),
}
Expand Down Expand Up @@ -234,3 +247,41 @@ func waitForTransferServerDeletion(conn *transfer.Transfer, serverID string) err
return resource.RetryableError(fmt.Errorf("Transfer Server (%s) still exists", serverID))
})
}

func deleteTransferUsers(conn *transfer.Transfer, serverID string, nextToken *string) error {
listOpts := &transfer.ListUsersInput{
ServerId: aws.String(serverID),
NextToken: nextToken,
}

log.Printf("[DEBUG] List Transfer User Option: %#v", listOpts)

resp, err := conn.ListUsers(listOpts)
if err != nil {
return err
}

for _, user := range resp.Users {

delOpts := &transfer.DeleteUserInput{
ServerId: aws.String(serverID),
UserName: user.UserName,
}

log.Printf("[DEBUG] Delete Transfer User Option: %#v", delOpts)

_, err = conn.DeleteUser(delOpts)
if err != nil {
if isAWSErr(err, transfer.ErrCodeResourceNotFoundException, "") {
continue
}
return fmt.Errorf("error deleting Transfer User (%s) for Server(%s): %s", *user.UserName, serverID, err)
}
}

if resp.NextToken != nil {
return deleteTransferUsers(conn, serverID, resp.NextToken)
}

return nil
}
125 changes: 122 additions & 3 deletions aws/resource_aws_transfer_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/transfer"

"github.com/hashicorp/terraform/helper/acctest"
Expand Down Expand Up @@ -36,9 +37,10 @@ func TestAccAWSTransferServer_basic(t *testing.T) {
),
},
{
ResourceName: "aws_transfer_server.foo",
ImportState: true,
ImportStateVerify: true,
ResourceName: "aws_transfer_server.foo",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_destroy"},
},
{
Config: testAccAWSTransferServerConfig_basicUpdate(rName),
Expand Down Expand Up @@ -108,6 +110,40 @@ func TestAccAWSTransferServer_disappears(t *testing.T) {
})
}

func TestAccAWSTransferServer_forcedestroy(t *testing.T) {
var conf transfer.DescribedServer
var roleConf iam.GetRoleOutput
rName := acctest.RandString(5)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_transfer_server.foo",
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSTransferServerDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSTransferServerConfig_forcedestroy(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSTransferServerExists("aws_transfer_server.foo", &conf),
testAccCheckAWSRoleExists("aws_iam_role.foo", &roleConf),
resource.TestCheckResourceAttr(
"aws_transfer_server.foo", "identity_provider_type", "SERVICE_MANAGED"),
resource.TestCheckResourceAttr(
"aws_transfer_server.foo", "force_destroy", "true"),
testAccCheckAWSTransferCreateUser(&conf, &roleConf, rName),
testAccCheckAWSTransferCreateSshKey(&conf, rName),
),
},
{
ResourceName: "aws_transfer_server.foo",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_destroy"},
},
},
})
}

func testAccCheckAWSTransferServerExists(n string, res *transfer.DescribedServer) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
Expand Down Expand Up @@ -177,6 +213,42 @@ func testAccCheckAWSTransferServerDestroy(s *terraform.State) error {
return nil
}

func testAccCheckAWSTransferCreateUser(describedServer *transfer.DescribedServer, getRoleOutput *iam.GetRoleOutput, userName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).transferconn

input := &transfer.CreateUserInput{
ServerId: describedServer.ServerId,
UserName: aws.String(userName),
Role: getRoleOutput.Role.Arn,
}

if _, err := conn.CreateUser(input); err != nil {
return fmt.Errorf("error creating Transfer User (%s) on Server (%s): %s", userName, aws.StringValue(describedServer.ServerId), err)
}

return nil
}
}

func testAccCheckAWSTransferCreateSshKey(describedServer *transfer.DescribedServer, userName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).transferconn

input := &transfer.ImportSshPublicKeyInput{
ServerId: describedServer.ServerId,
UserName: aws.String(userName),
SshPublicKeyBody: aws.String("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 phodgson@thoughtworks.com"),
}

if _, err := conn.ImportSshPublicKey(input); err != nil {
return fmt.Errorf("error creating Transfer SSH Public Key for (%s/%s): %s", userName, aws.StringValue(describedServer.ServerId), err)
}

return nil
}
}

const testAccAWSTransferServerConfig_basic = `
resource "aws_transfer_server" "foo" {}
`
Expand Down Expand Up @@ -348,3 +420,50 @@ resource "aws_transfer_server" "foo" {
`, rName, rName, rName, rName)

}

func testAccAWSTransferServerConfig_forcedestroy(rName string) string {
return fmt.Sprintf(`
resource "aws_transfer_server" "foo" {
force_destroy = true
}

resource "aws_iam_role" "foo" {
name = "tf-test-transfer-user-iam-role-%s"

assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "transfer.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
}

resource "aws_iam_role_policy" "foo" {
name = "tf-test-transfer-user-iam-policy-%s"
role = "${aws_iam_role.foo.id}"
policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowFullAccesstoS3",
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": "*"
}
]
}
POLICY
}
`, rName, rName)
}
1 change: 1 addition & 0 deletions website/docs/r/transfer_server.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ The following arguments are supported:
* `url` - (Optional) - URL of the service endpoint used to authenticate users with an `identity_provider_type` of `API_GATEWAY`.
* `identity_provider_type` - (Optional) The mode of authentication enabled for this service. The default value is `SERVICE_MANAGED`, which allows you to store and access SFTP user credentials within the service. `API_GATEWAY` indicates that user authentication requires a call to an API Gateway endpoint URL provided by you to integrate an identity provider of your choice.
* `logging_role` - (Optional) Amazon Resource Name (ARN) of an IAM role that allows the service to write your SFTP users’ activity to your Amazon CloudWatch logs for monitoring and auditing purposes.
* `force_destroy` - (Optional) A boolean that indicates all users associated with the server should be deleted so that the Server can be destroyed without error. The default value is `false`.
* `tags` - (Optional) A mapping of tags to assign to the resource.

## Attributes Reference
Expand Down