github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/commands/tls/custom/certificate/create.go (about)

     1  package certificate
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/fastly/go-fastly/v9/fastly"
     7  
     8  	"github.com/fastly/cli/pkg/argparser"
     9  	"github.com/fastly/cli/pkg/global"
    10  	"github.com/fastly/cli/pkg/text"
    11  )
    12  
    13  // NewCreateCommand returns a usable command registered under the parent.
    14  func NewCreateCommand(parent argparser.Registerer, g *global.Data) *CreateCommand {
    15  	var c CreateCommand
    16  	c.CmdClause = parent.Command("create", "Create a TLS certificate").Alias("add")
    17  	c.Globals = g
    18  
    19  	// Required.
    20  	c.CmdClause.Flag("cert-blob", "The PEM-formatted certificate blob").Required().StringVar(&c.certBlob)
    21  
    22  	// Optional.
    23  	c.CmdClause.Flag("id", "Alphanumeric string identifying a TLS certificate").StringVar(&c.id)
    24  	c.CmdClause.Flag("name", "A customizable name for your certificate. Defaults to the certificate's Common Name or first Subject Alternative Names (SAN) entry").StringVar(&c.name)
    25  
    26  	return &c
    27  }
    28  
    29  // CreateCommand calls the Fastly API to create an appropriate resource.
    30  type CreateCommand struct {
    31  	argparser.Base
    32  
    33  	certBlob string
    34  	id       string
    35  	name     string
    36  }
    37  
    38  // Exec invokes the application logic for the command.
    39  func (c *CreateCommand) Exec(_ io.Reader, out io.Writer) error {
    40  	input := c.constructInput()
    41  
    42  	r, err := c.Globals.APIClient.CreateCustomTLSCertificate(input)
    43  	if err != nil {
    44  		c.Globals.ErrLog.AddWithContext(err, map[string]any{
    45  			"TLS Certificate ID":   c.id,
    46  			"TLS Certificate Name": c.name,
    47  		})
    48  		return err
    49  	}
    50  
    51  	text.Success(out, "Created TLS Certificate '%s'", r.ID)
    52  	return nil
    53  }
    54  
    55  // constructInput transforms values parsed from CLI flags into an object to be used by the API client library.
    56  func (c *CreateCommand) constructInput() *fastly.CreateCustomTLSCertificateInput {
    57  	var input fastly.CreateCustomTLSCertificateInput
    58  
    59  	if c.id != "" {
    60  		input.ID = c.id
    61  	}
    62  	input.CertBlob = c.certBlob
    63  	if c.name != "" {
    64  		input.Name = c.name
    65  	}
    66  
    67  	return &input
    68  }