agent.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package aws
  2. import (
  3. "github.com/aws/aws-sdk-go/aws/session"
  4. "github.com/aws/aws-sdk-go/service/iam"
  5. "github.com/porter-dev/porter/cli/cmd/utils"
  6. "k8s.io/client-go/kubernetes"
  7. )
  8. type Agent struct {
  9. Session *session.Session
  10. IAMService *iam.IAM
  11. Clientset kubernetes.Interface
  12. }
  13. type PorterAWSCredentials struct {
  14. AWSAccessKeyID string `json:"aws_access_key_id"`
  15. AWSSecretAccessKey string `json:"aws_secret_access_key"`
  16. AWSClusterID string `json:"aws_cluster_id"`
  17. }
  18. func (a *Agent) CreateIAMKubernetesMapping(clusterIDGuess string) (*PorterAWSCredentials, error) {
  19. // (1) Create a new IAM user called porter-dashboard-[random_string], and attach the policy:
  20. //
  21. // arn:aws:iam::aws:policy/AmazonEKSClusterPolicy
  22. name := "porter-dashboard-" + utils.StringWithCharset(6, "abcdefghijklmnopqrstuvwxyz1234567890")
  23. user, err := a.IAMService.CreateUser(&iam.CreateUserInput{
  24. UserName: &name,
  25. })
  26. if err != nil {
  27. return nil, err
  28. }
  29. policyArn := "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
  30. _, err = a.IAMService.AttachUserPolicy(&iam.AttachUserPolicyInput{
  31. PolicyArn: &policyArn,
  32. UserName: &name,
  33. })
  34. if err != nil {
  35. return nil, err
  36. }
  37. // (2) Create an access key for the porter-dashboard-[random_string] user and return the
  38. // access key and secret. Use the guessed cluster ID.
  39. resp, err := a.IAMService.CreateAccessKey(&iam.CreateAccessKeyInput{
  40. UserName: &name,
  41. })
  42. if err != nil {
  43. return nil, err
  44. }
  45. porterCreds := &PorterAWSCredentials{
  46. AWSAccessKeyID: *resp.AccessKey.AccessKeyId,
  47. AWSSecretAccessKey: *resp.AccessKey.SecretAccessKey,
  48. AWSClusterID: clusterIDGuess,
  49. }
  50. // (3) Use the eksctl authconfigmap package to map this user to a cluster identity.
  51. authCm, err := NewFromClientSet(a.Clientset)
  52. if err != nil {
  53. return nil, err
  54. }
  55. identity, err := NewIdentity(
  56. *user.User.Arn,
  57. "admin",
  58. []string{"system:masters"},
  59. )
  60. if err != nil {
  61. return nil, err
  62. }
  63. err = authCm.AddIdentity(identity)
  64. if err != nil {
  65. return nil, err
  66. }
  67. err = authCm.Save()
  68. if err != nil {
  69. return nil, err
  70. }
  71. return porterCreds, nil
  72. }