Skip to content

Commit 22a409e

Browse files
committed
Merge pull request hashicorp#5774 from stack72/f-aws-iam-user-sshkey
provider/aws: Add `aws_iam_user_ssh_key` resource
2 parents 12546c6 + 49c5137 commit 22a409e

5 files changed

Lines changed: 344 additions & 0 deletions

File tree

builtin/providers/aws/provider.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ func Provider() terraform.ResourceProvider {
179179
"aws_iam_saml_provider": resourceAwsIamSamlProvider(),
180180
"aws_iam_server_certificate": resourceAwsIAMServerCertificate(),
181181
"aws_iam_user_policy": resourceAwsIamUserPolicy(),
182+
"aws_iam_user_ssh_key": resourceAwsIamUserSshKey(),
182183
"aws_iam_user": resourceAwsIamUser(),
183184
"aws_instance": resourceAwsInstance(),
184185
"aws_internet_gateway": resourceAwsInternetGateway(),
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
package aws
2+
3+
import (
4+
"fmt"
5+
"log"
6+
7+
"github.com/aws/aws-sdk-go/aws"
8+
"github.com/aws/aws-sdk-go/aws/awserr"
9+
"github.com/aws/aws-sdk-go/service/iam"
10+
11+
"github.com/hashicorp/terraform/helper/schema"
12+
)
13+
14+
func resourceAwsIamUserSshKey() *schema.Resource {
15+
return &schema.Resource{
16+
Create: resourceAwsIamUserSshKeyCreate,
17+
Read: resourceAwsIamUserSshKeyRead,
18+
Update: resourceAwsIamUserSshKeyUpdate,
19+
Delete: resourceAwsIamUserSshKeyDelete,
20+
21+
Schema: map[string]*schema.Schema{
22+
"ssh_public_key_id": &schema.Schema{
23+
Type: schema.TypeString,
24+
Computed: true,
25+
},
26+
"fingerprint": &schema.Schema{
27+
Type: schema.TypeString,
28+
Computed: true,
29+
},
30+
"username": &schema.Schema{
31+
Type: schema.TypeString,
32+
Required: true,
33+
ForceNew: true,
34+
},
35+
"public_key": &schema.Schema{
36+
Type: schema.TypeString,
37+
Required: true,
38+
},
39+
40+
"encoding": &schema.Schema{
41+
Type: schema.TypeString,
42+
Required: true,
43+
ValidateFunc: validateIamUserSSHKeyEncoding,
44+
},
45+
46+
"status": &schema.Schema{
47+
Type: schema.TypeString,
48+
Optional: true,
49+
Computed: true,
50+
},
51+
},
52+
}
53+
}
54+
55+
func resourceAwsIamUserSshKeyCreate(d *schema.ResourceData, meta interface{}) error {
56+
iamconn := meta.(*AWSClient).iamconn
57+
username := d.Get("username").(string)
58+
publicKey := d.Get("public_key").(string)
59+
60+
request := &iam.UploadSSHPublicKeyInput{
61+
UserName: aws.String(username),
62+
SSHPublicKeyBody: aws.String(publicKey),
63+
}
64+
65+
log.Println("[DEBUG] Create IAM User SSH Key Request:", request)
66+
createResp, err := iamconn.UploadSSHPublicKey(request)
67+
if err != nil {
68+
return fmt.Errorf("Error creating IAM User SSH Key %s: %s", username, err)
69+
}
70+
71+
d.Set("ssh_public_key_id", createResp.SSHPublicKey.SSHPublicKeyId)
72+
d.SetId(*createResp.SSHPublicKey.SSHPublicKeyId)
73+
74+
return resourceAwsIamUserSshKeyRead(d, meta)
75+
}
76+
77+
func resourceAwsIamUserSshKeyRead(d *schema.ResourceData, meta interface{}) error {
78+
iamconn := meta.(*AWSClient).iamconn
79+
username := d.Get("username").(string)
80+
request := &iam.GetSSHPublicKeyInput{
81+
UserName: aws.String(username),
82+
SSHPublicKeyId: aws.String(d.Id()),
83+
Encoding: aws.String(d.Get("encoding").(string)),
84+
}
85+
86+
getResp, err := iamconn.GetSSHPublicKey(request)
87+
if err != nil {
88+
if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { // XXX test me
89+
log.Printf("[WARN] No IAM user ssh key (%s) found", d.Id())
90+
d.SetId("")
91+
return nil
92+
}
93+
return fmt.Errorf("Error reading IAM User SSH Key %s: %s", d.Id(), err)
94+
}
95+
96+
d.Set("fingerprint", getResp.SSHPublicKey.Fingerprint)
97+
d.Set("status", getResp.SSHPublicKey.Status)
98+
99+
return nil
100+
}
101+
102+
func resourceAwsIamUserSshKeyUpdate(d *schema.ResourceData, meta interface{}) error {
103+
if d.HasChange("status") {
104+
iamconn := meta.(*AWSClient).iamconn
105+
106+
request := &iam.UpdateSSHPublicKeyInput{
107+
UserName: aws.String(d.Get("username").(string)),
108+
SSHPublicKeyId: aws.String(d.Id()),
109+
Status: aws.String(d.Get("status").(string)),
110+
}
111+
112+
log.Println("[DEBUG] Update IAM User SSH Key request:", request)
113+
_, err := iamconn.UpdateSSHPublicKey(request)
114+
if err != nil {
115+
if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
116+
log.Printf("[WARN] No IAM user ssh key by ID (%s) found", d.Id())
117+
d.SetId("")
118+
return nil
119+
}
120+
return fmt.Errorf("Error updating IAM User SSH Key %s: %s", d.Id(), err)
121+
}
122+
return resourceAwsIamUserRead(d, meta)
123+
}
124+
return nil
125+
}
126+
127+
func resourceAwsIamUserSshKeyDelete(d *schema.ResourceData, meta interface{}) error {
128+
iamconn := meta.(*AWSClient).iamconn
129+
130+
request := &iam.DeleteSSHPublicKeyInput{
131+
UserName: aws.String(d.Get("username").(string)),
132+
SSHPublicKeyId: aws.String(d.Id()),
133+
}
134+
135+
log.Println("[DEBUG] Delete IAM User SSH Key request:", request)
136+
if _, err := iamconn.DeleteSSHPublicKey(request); err != nil {
137+
return fmt.Errorf("Error deleting IAM User SSH Key %s: %s", d.Id(), err)
138+
}
139+
return nil
140+
}
141+
142+
func validateIamUserSSHKeyEncoding(v interface{}, k string) (ws []string, errors []error) {
143+
value := v.(string)
144+
encodingTypes := map[string]bool{
145+
"PEM": true,
146+
"SSH": true,
147+
}
148+
149+
if !encodingTypes[value] {
150+
errors = append(errors, fmt.Errorf("IAM User SSH Key Encoding can only be PEM or SSH"))
151+
}
152+
return
153+
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
package aws
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/aws/aws-sdk-go/aws"
8+
"github.com/aws/aws-sdk-go/aws/awserr"
9+
"github.com/aws/aws-sdk-go/service/iam"
10+
"github.com/hashicorp/terraform/helper/acctest"
11+
"github.com/hashicorp/terraform/helper/resource"
12+
"github.com/hashicorp/terraform/terraform"
13+
)
14+
15+
func TestAccAWSUserSSHKey_basic(t *testing.T) {
16+
var conf iam.GetSSHPublicKeyOutput
17+
18+
ri := acctest.RandInt()
19+
config := fmt.Sprintf(testAccAWSSSHKeyConfig_sshEncoding, ri)
20+
21+
resource.Test(t, resource.TestCase{
22+
PreCheck: func() { testAccPreCheck(t) },
23+
Providers: testAccProviders,
24+
CheckDestroy: testAccCheckAWSUserSSHKeyDestroy,
25+
Steps: []resource.TestStep{
26+
resource.TestStep{
27+
Config: config,
28+
Check: resource.ComposeTestCheckFunc(
29+
testAccCheckAWSUserSSHKeyExists("aws_iam_user_ssh_key.user", &conf),
30+
),
31+
},
32+
},
33+
})
34+
}
35+
36+
func TestAccAWSUserSSHKey_pemEncoding(t *testing.T) {
37+
var conf iam.GetSSHPublicKeyOutput
38+
39+
ri := acctest.RandInt()
40+
config := fmt.Sprintf(testAccAWSSSHKeyConfig_pemEncoding, ri)
41+
42+
resource.Test(t, resource.TestCase{
43+
PreCheck: func() { testAccPreCheck(t) },
44+
Providers: testAccProviders,
45+
CheckDestroy: testAccCheckAWSUserSSHKeyDestroy,
46+
Steps: []resource.TestStep{
47+
resource.TestStep{
48+
Config: config,
49+
Check: resource.ComposeTestCheckFunc(
50+
testAccCheckAWSUserSSHKeyExists("aws_iam_user_ssh_key.user", &conf),
51+
),
52+
},
53+
},
54+
})
55+
}
56+
57+
func testAccCheckAWSUserSSHKeyDestroy(s *terraform.State) error {
58+
iamconn := testAccProvider.Meta().(*AWSClient).iamconn
59+
60+
for _, rs := range s.RootModule().Resources {
61+
if rs.Type != "aws_iam_user_ssh_key" {
62+
continue
63+
}
64+
65+
username := rs.Primary.Attributes["username"]
66+
encoding := rs.Primary.Attributes["encoding"]
67+
_, err := iamconn.GetSSHPublicKey(&iam.GetSSHPublicKeyInput{
68+
SSHPublicKeyId: aws.String(rs.Primary.ID),
69+
UserName: aws.String(username),
70+
Encoding: aws.String(encoding),
71+
})
72+
if err == nil {
73+
return fmt.Errorf("still exist.")
74+
}
75+
76+
// Verify the error is what we want
77+
ec2err, ok := err.(awserr.Error)
78+
if !ok {
79+
return err
80+
}
81+
if ec2err.Code() != "NoSuchEntity" {
82+
return err
83+
}
84+
}
85+
86+
return nil
87+
}
88+
89+
func testAccCheckAWSUserSSHKeyExists(n string, res *iam.GetSSHPublicKeyOutput) resource.TestCheckFunc {
90+
return func(s *terraform.State) error {
91+
rs, ok := s.RootModule().Resources[n]
92+
if !ok {
93+
return fmt.Errorf("Not found: %s", n)
94+
}
95+
96+
if rs.Primary.ID == "" {
97+
return fmt.Errorf("No SSHPublicKeyID is set")
98+
}
99+
100+
iamconn := testAccProvider.Meta().(*AWSClient).iamconn
101+
102+
username := rs.Primary.Attributes["username"]
103+
encoding := rs.Primary.Attributes["encoding"]
104+
resp, err := iamconn.GetSSHPublicKey(&iam.GetSSHPublicKeyInput{
105+
SSHPublicKeyId: aws.String(rs.Primary.ID),
106+
UserName: aws.String(username),
107+
Encoding: aws.String(encoding),
108+
})
109+
if err != nil {
110+
return err
111+
}
112+
113+
*res = *resp
114+
115+
return nil
116+
}
117+
}
118+
119+
const testAccAWSSSHKeyConfig_sshEncoding = `
120+
resource "aws_iam_user" "user" {
121+
name = "test-user-%d"
122+
path = "/"
123+
}
124+
125+
resource "aws_iam_user_ssh_key" "user" {
126+
username = "${aws_iam_user.user.name}"
127+
encoding = "SSH"
128+
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 phodgson@thoughtworks.com"
129+
}
130+
`
131+
132+
const testAccAWSSSHKeyConfig_pemEncoding = `
133+
resource "aws_iam_user" "user" {
134+
name = "test-user-%d"
135+
path = "/"
136+
}
137+
138+
resource "aws_iam_user_ssh_key" "user" {
139+
username = "${aws_iam_user.user.name}"
140+
encoding = "PEM"
141+
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 phodgson@thoughtworks.com"
142+
}
143+
`
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
layout: "aws"
3+
page_title: "AWS: aws_iam_user_ssh_key"
4+
sidebar_current: "docs-aws-resource-iam-user-ssh-key"
5+
description: |-
6+
Uploads an SSH public key and associates it with the specified IAM user.
7+
---
8+
9+
# aws\_iam\_user\_ssh\_key
10+
11+
Uploads an SSH public key and associates it with the specified IAM user.
12+
13+
## Example Usage
14+
15+
```
16+
resource "aws_iam_user" "user" {
17+
name = "test-user"
18+
path = "/"
19+
}
20+
21+
resource "aws_iam_user_ssh_key" "user" {
22+
username = "${aws_iam_user.user.name}"
23+
encoding = "PEM"
24+
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 mytest@mydomain.com"
25+
}
26+
```
27+
28+
## Argument Reference
29+
30+
The following arguments are supported:
31+
32+
* `username` - (Required) The name of the IAM user to associate the SSH public key with.
33+
* `encoding` - (Required) Specifies the public key encoding format to use in the response. To retrieve the public key in ssh-rsa format, use SSH . To retrieve the public key in PEM format, use PEM .
34+
* `public_key` - (Required) The SSH public key. The public key must be encoded in ssh-rsa format or PEM format.
35+
* `status` - (Optional) The status to assign to the SSH public key. Active means the key can be used for authentication with an AWS CodeCommit repository. Inactive means the key cannot be used. Default is `active`.
36+
37+
## Attributes Reference
38+
39+
The following attributes are exported:
40+
41+
* `ssh_public_key_id` - The unique identifier for the SSH public key.
42+
* `fingerprint` - The MD5 message digest of the SSH public key.
43+

website/source/layouts/aws.erb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,10 @@
388388
<a href="/docs/providers/aws/r/iam_user_policy.html">aws_iam_user_policy</a>
389389
</li>
390390

391+
<li<%= sidebar_current("docs-aws-resource-iam-user-ssh-key") %>>
392+
<a href="/docs/providers/aws/r/iam_user_ssh_key.html">aws_iam_user_ssh_key</a>
393+
</li>
394+
391395
</ul>
392396
</li>
393397

0 commit comments

Comments
 (0)