|
| 1 | +package key |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + awssdk "github.com/aws/aws-sdk-go-v2/aws" |
| 8 | + "github.com/awslabs/eksdemo/pkg/aws" |
| 9 | + "github.com/awslabs/eksdemo/pkg/resource" |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +type Manager struct { |
| 14 | + DryRun bool |
| 15 | + kmsClient *aws.KMSClient |
| 16 | + kmsGetter *Getter |
| 17 | +} |
| 18 | + |
| 19 | +func (m *Manager) Init() { |
| 20 | + if m.kmsClient == nil { |
| 21 | + m.kmsClient = aws.NewKMSClient() |
| 22 | + } |
| 23 | + m.kmsGetter = NewGetter(m.kmsClient) |
| 24 | +} |
| 25 | + |
| 26 | +func (m *Manager) Create(options resource.Options) error { |
| 27 | + alias := options.Common().Name |
| 28 | + |
| 29 | + _, err := m.kmsGetter.GetByAlias(alias) |
| 30 | + |
| 31 | + // Return if the KMS alias already exists |
| 32 | + if err == nil { |
| 33 | + fmt.Printf("KMS Key with alias %q already exists\n", alias) |
| 34 | + return nil |
| 35 | + } |
| 36 | + |
| 37 | + // Return the error if it's anything other than resource not found |
| 38 | + var notFoundErr *resource.NotFoundByError |
| 39 | + if !errors.As(err, ¬FoundErr) { |
| 40 | + return err |
| 41 | + } |
| 42 | + |
| 43 | + fullAliasName := fmt.Sprintf("alias/%s", alias) |
| 44 | + |
| 45 | + if m.DryRun { |
| 46 | + return m.dryRun(fullAliasName) |
| 47 | + } |
| 48 | + |
| 49 | + fmt.Printf("Creating KMS Key with Alias %q...", alias) |
| 50 | + |
| 51 | + keyMeta, err := m.kmsClient.CreateKey() |
| 52 | + if err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + |
| 56 | + keyID := awssdk.ToString(keyMeta.KeyId) |
| 57 | + |
| 58 | + err = m.kmsClient.CreateAlias(fullAliasName, keyID) |
| 59 | + if err != nil { |
| 60 | + return fmt.Errorf("failed to create alias for key %q: %w", keyID, err) |
| 61 | + } |
| 62 | + fmt.Printf("done\nCreated KMS Key Id: %s\n", keyID) |
| 63 | + |
| 64 | + return nil |
| 65 | +} |
| 66 | + |
| 67 | +func (m *Manager) Delete(_ resource.Options) error { |
| 68 | + return fmt.Errorf("feature not supported") |
| 69 | +} |
| 70 | + |
| 71 | +func (m *Manager) SetDryRun() { |
| 72 | + m.DryRun = true |
| 73 | +} |
| 74 | + |
| 75 | +func (m *Manager) Update(_ resource.Options, _ *cobra.Command) error { |
| 76 | + return fmt.Errorf("feature not supported") |
| 77 | +} |
| 78 | + |
| 79 | +func (m *Manager) dryRun(aliasName string) error { |
| 80 | + fmt.Printf("\nKMS Key Manager Dry Run:\n") |
| 81 | + fmt.Printf("KMS API Call %q with no request parameters\n", "CreateKey") |
| 82 | + fmt.Printf("KMS API Call %q with parameters:\n", "CreateAlias") |
| 83 | + fmt.Printf("\tAliasName: %q\n", aliasName) |
| 84 | + fmt.Printf("\tTargetKeyId: <Key Id returned from CreateKey call>\n") |
| 85 | + return nil |
| 86 | +} |
0 commit comments