github.com/Venafi/vcert/v5@v5.10.2/examples/tlspc-svc-account/main.go (about) 1 package main 2 3 import ( 4 "crypto/x509/pkix" 5 "fmt" 6 "log" 7 "os" 8 9 "github.com/Venafi/vcert/v5" 10 "github.com/Venafi/vcert/v5/pkg/certificate" 11 "github.com/Venafi/vcert/v5/pkg/endpoint" 12 "github.com/Venafi/vcert/v5/pkg/util" 13 ) 14 15 const ( 16 vcpURL = "VCP_URL" 17 vcpZone = "VCP_ZONE" 18 vcpTokenURL = "VCP_TOKEN_URL" // #nosec G101 // This is not a hardcoded credential 19 vcpJWT = "VCP_JWT" 20 21 envVarNotSet = "environment variable not set: %s" 22 23 name = "example-tlspc-service-account-client" 24 version = "v0.0.1" 25 ) 26 27 func main() { 28 29 // URL can be nil if using production TLSPC 30 url := os.Getenv(vcpURL) 31 32 zone, found := os.LookupEnv(vcpZone) 33 if !found { 34 log.Fatalf(envVarNotSet, vcpZone) 35 } 36 tokenURL, found := os.LookupEnv(vcpTokenURL) 37 if !found { 38 log.Fatalf(envVarNotSet, vcpTokenURL) 39 } 40 jwt, found := os.LookupEnv(vcpJWT) 41 if !found { 42 log.Fatalf(envVarNotSet, vcpJWT) 43 } 44 45 userAgent := fmt.Sprintf("%s/%s %s", name, version, util.DefaultUserAgent) 46 config := &vcert.Config{ 47 ConnectorType: endpoint.ConnectorTypeCloud, 48 BaseUrl: url, 49 Zone: zone, 50 Credentials: &endpoint.Authentication{ 51 ExternalJWT: jwt, 52 TokenURL: tokenURL, 53 }, 54 UserAgent: &userAgent, 55 } 56 connector, err := vcert.NewClient(config) 57 if err != nil { 58 log.Fatalf("error creating client: %s", err.Error()) 59 } 60 61 zoneConfig, err := connector.ReadZoneConfiguration() 62 if err != nil { 63 log.Fatalf("error reading zone: %s", err.Error()) 64 } 65 66 request := &certificate.Request{ 67 Subject: pkix.Name{ 68 CommonName: "svc-account.venafi.example.com", 69 }, 70 CsrOrigin: certificate.LocalGeneratedCSR, 71 KeyType: certificate.KeyTypeRSA, 72 KeyLength: 2048, 73 } 74 75 err = connector.GenerateRequest(zoneConfig, request) 76 if err != nil { 77 log.Fatalf("error generating request: %s", err.Error()) 78 } 79 80 certID, err := connector.RequestCertificate(request) 81 if err != nil { 82 log.Fatalf("error requesting certificate: %s", err.Error()) 83 } 84 log.Printf("certificate requested with ID: %s", certID) 85 86 pcc, err := connector.RetrieveCertificate(request) 87 if err != nil { 88 log.Fatalf("error retrieving certificate: %s", err.Error()) 89 } 90 log.Printf("Certificate:\n%s", pcc.Certificate) 91 }