Documentation
¶
Overview ¶
Package cinc is a Go client for the Chef Infra / CINC Server API.
Construct a Client with NewClient, then call methods on its service fields:
key, _ := cinc.LoadKeyFile("/etc/chef/client.pem")
c, _ := cinc.NewClient(cinc.Config{
ServerURL: "https://chef.example.com",
Org: "myorg",
ClientName: "node1",
Key: key,
})
node, _, err := c.Nodes.Get(context.Background(), "web01")
Requests are authenticated with the Chef v1.3 signed-header protocol.
Index ¶
- Variables
- func ExpandPerm(perm string) ([]string, error)
- func GenerateKeyPair() (privatePEM, publicPEM string, err error)
- func LoadKeyFile(path string) (*rsa.PrivateKey, error)
- func ParseKey(pemBytes []byte) (*rsa.PrivateKey, error)
- func ParseServerURL(raw string) (serverURL, org string, err error)
- type ACE
- type ACL
- type ACLsService
- func (s *ACLsService) Get(ctx context.Context, objectType, name string) (*ACL, *Response, error)
- func (s *ACLsService) GetOrg(ctx context.Context) (*ACL, *Response, error)
- func (s *ACLsService) GetUser(ctx context.Context, name string) (*ACL, *Response, error)
- func (s *ACLsService) SetOrgPermission(ctx context.Context, perm string, ace *ACE) error
- func (s *ACLsService) SetPermission(ctx context.Context, objectType, name, perm string, ace *ACE) error
- func (s *ACLsService) SetUserPermission(ctx context.Context, name, perm string, ace *ACE) error
- type APIClient
- type AssociationsService
- func (s *AssociationsService) AddMember(ctx context.Context, username string) (*Response, error)
- func (s *AssociationsService) GetMember(ctx context.Context, name string) (*OrgUser, *Response, error)
- func (s *AssociationsService) Invite(ctx context.Context, username string) (*InviteResult, *Response, error)
- func (s *AssociationsService) ListInvites(ctx context.Context) ([]Invitation, *Response, error)
- func (s *AssociationsService) ListMembers(ctx context.Context) ([]string, *Response, error)
- func (s *AssociationsService) ListUserInvites(ctx context.Context, username string) ([]Invitation, *Response, error)
- func (s *AssociationsService) ListUserOrgs(ctx context.Context, username string) ([]Org, *Response, error)
- func (s *AssociationsService) RemoveMember(ctx context.Context, name string) (*OrgUser, *Response, error)
- func (s *AssociationsService) RescindInvite(ctx context.Context, id string) (*Response, error)
- func (s *AssociationsService) RespondInvite(ctx context.Context, username, id string, accept bool) (*Response, error)
- func (s *AssociationsService) UserInviteCount(ctx context.Context, username string) (int, *Response, error)
- type Attributes
- type ChefKey
- type Chefignore
- type Client
- type ClientsService
- func (s *ClientsService) Create(ctx context.Context, cl *APIClient) (*APIClient, *Response, error)
- func (s *ClientsService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *ClientsService) Get(ctx context.Context, name string) (*APIClient, *Response, error)
- func (s *ClientsService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *ClientsService) Reregister(ctx context.Context, name string) (*Key, *Response, error)
- func (s *ClientsService) Update(ctx context.Context, cl *APIClient) (*APIClient, *Response, error)
- type Config
- type Container
- type ContainersService
- func (s *ContainersService) Create(ctx context.Context, name string) (*Response, error)
- func (s *ContainersService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *ContainersService) Get(ctx context.Context, name string) (*Container, *Response, error)
- func (s *ContainersService) List(ctx context.Context) (map[string]string, *Response, error)
- type Cookbook
- type CookbookArtifactListEntry
- type CookbookArtifactVersion
- type CookbookArtifactsService
- func (s *CookbookArtifactsService) Delete(ctx context.Context, name, identifier string) (*Response, error)
- func (s *CookbookArtifactsService) Get(ctx context.Context, name, identifier string) (*Cookbook, *Response, error)
- func (s *CookbookArtifactsService) GetVersions(ctx context.Context, name string) (*CookbookArtifactListEntry, *Response, error)
- func (s *CookbookArtifactsService) List(ctx context.Context) (map[string]CookbookArtifactListEntry, *Response, error)
- func (s *CookbookArtifactsService) Upload(ctx context.Context, cb *LocalCookbook, identifier string) error
- type CookbookFileRef
- type CookbookListEntry
- type CookbookLock
- type CookbookMetadata
- type CookbookVersion
- type CookbooksService
- func (s *CookbooksService) Delete(ctx context.Context, name, version string) (*Response, error)
- func (s *CookbooksService) Download(ctx context.Context, name, version, destDir string) error
- func (s *CookbooksService) Get(ctx context.Context, name, version string) (*Cookbook, *Response, error)
- func (s *CookbooksService) GetVersions(ctx context.Context, name, numVersions string) (*CookbookListEntry, *Response, error)
- func (s *CookbooksService) List(ctx context.Context) (map[string]CookbookListEntry, *Response, error)
- func (s *CookbooksService) ListLatest(ctx context.Context) (map[string]string, *Response, error)
- func (s *CookbooksService) ListRecipes(ctx context.Context) ([]string, *Response, error)
- func (s *CookbooksService) Upload(ctx context.Context, cb *LocalCookbook) error
- type DataBagItem
- type DataBagItemsService
- func (s *DataBagItemsService) Create(ctx context.Context, item DataBagItem) (DataBagItem, *Response, error)
- func (s *DataBagItemsService) Delete(ctx context.Context, id string) (*Response, error)
- func (s *DataBagItemsService) Get(ctx context.Context, id string) (DataBagItem, *Response, error)
- func (s *DataBagItemsService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *DataBagItemsService) Update(ctx context.Context, item DataBagItem) (DataBagItem, *Response, error)
- type DataBagsService
- func (s *DataBagsService) Create(ctx context.Context, name string) (*Response, error)
- func (s *DataBagsService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *DataBagsService) Items(bag string) *DataBagItemsService
- func (s *DataBagsService) List(ctx context.Context) (map[string]string, *Response, error)
- type Environment
- type EnvironmentsService
- func (s *EnvironmentsService) CookbookVersions(ctx context.Context, env string, runList []string) (map[string]Cookbook, *Response, error)
- func (s *EnvironmentsService) Create(ctx context.Context, e *Environment) (*Response, error)
- func (s *EnvironmentsService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *EnvironmentsService) Get(ctx context.Context, name string) (*Environment, *Response, error)
- func (s *EnvironmentsService) GetCookbook(ctx context.Context, env, name, numVersions string) (map[string]CookbookListEntry, *Response, error)
- func (s *EnvironmentsService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *EnvironmentsService) ListCookbooks(ctx context.Context, env, numVersions string) (map[string]CookbookListEntry, *Response, error)
- func (s *EnvironmentsService) ListNodes(ctx context.Context, env string) (map[string]string, *Response, error)
- func (s *EnvironmentsService) ListRecipes(ctx context.Context, env string) ([]string, *Response, error)
- func (s *EnvironmentsService) RoleRunList(ctx context.Context, env, role string) ([]string, *Response, error)
- func (s *EnvironmentsService) Update(ctx context.Context, e *Environment) (*Environment, *Response, error)
- type ErrorResponse
- type Group
- type GroupsService
- func (s *GroupsService) Create(ctx context.Context, name string) (*Response, error)
- func (s *GroupsService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *GroupsService) Get(ctx context.Context, name string) (*Group, *Response, error)
- func (s *GroupsService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *GroupsService) Update(ctx context.Context, g *Group) (*Group, *Response, error)
- type Invitation
- type InviteResult
- type Key
- type KeyScope
- func (s *KeyScope) Create(ctx context.Context, k *Key) (*Key, *Response, error)
- func (s *KeyScope) Delete(ctx context.Context, name string) (*Response, error)
- func (s *KeyScope) Get(ctx context.Context, name string) (*Key, *Response, error)
- func (s *KeyScope) List(ctx context.Context) ([]Key, *Response, error)
- func (s *KeyScope) Update(ctx context.Context, name string, k *Key) (*Key, *Response, error)
- type KeygenStatus
- type KeysService
- type License
- type LicenseService
- type LocalCookbook
- type Node
- func (n *Node) AddRunListItems(items ...string)
- func (n *Node) AddTags(tags ...string)
- func (n *Node) Attribute(name string) (any, bool)
- func (n *Node) AttributeString(name string) string
- func (n Node) MarshalJSON() ([]byte, error)
- func (n *Node) RemoveRunListItems(items ...string)
- func (n *Node) RemoveTags(tags ...string)
- func (n *Node) SetTags(tags []string)
- func (n *Node) Tags() []string
- type NodesService
- func (s *NodesService) Create(ctx context.Context, n *Node) (*Response, error)
- func (s *NodesService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *NodesService) Get(ctx context.Context, name string) (*Node, *Response, error)
- func (s *NodesService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *NodesService) Update(ctx context.Context, n *Node) (*Node, *Response, error)
- type Option
- type Org
- type OrgCreateResult
- type OrgUser
- type OrgsService
- func (s *OrgsService) Create(ctx context.Context, o *Org) (*OrgCreateResult, *Response, error)
- func (s *OrgsService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *OrgsService) Get(ctx context.Context, name string) (*Org, *Response, error)
- func (s *OrgsService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *OrgsService) Update(ctx context.Context, o *Org) (*Org, *Response, error)
- type PoliciesService
- func (s *PoliciesService) CreateRevision(ctx context.Context, name string, doc any) (*PolicyRevision, *Response, error)
- func (s *PoliciesService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *PoliciesService) DeleteRevision(ctx context.Context, name, revisionID string) (*Response, error)
- func (s *PoliciesService) Get(ctx context.Context, name string) (*PolicyRevisions, *Response, error)
- func (s *PoliciesService) GetRevision(ctx context.Context, name, revisionID string) (*PolicyRevision, *Response, error)
- func (s *PoliciesService) List(ctx context.Context) (map[string]PolicyListEntry, *Response, error)
- func (s *PoliciesService) PushRevision(ctx context.Context, lockJSON []byte, group string, ...) (*PolicyRevision, *Response, error)
- type PolicyAssignment
- type PolicyGroup
- type PolicyGroupsService
- func (s *PolicyGroupsService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *PolicyGroupsService) DeletePolicy(ctx context.Context, group, policy string) (*Response, error)
- func (s *PolicyGroupsService) Get(ctx context.Context, name string) (*PolicyGroup, *Response, error)
- func (s *PolicyGroupsService) GetPolicy(ctx context.Context, group, policy string) (*PolicyRevision, *Response, error)
- func (s *PolicyGroupsService) List(ctx context.Context) (map[string]PolicyGroup, *Response, error)
- func (s *PolicyGroupsService) PutPolicy(ctx context.Context, group, policy string, doc any) (*PolicyRevision, *Response, error)
- type PolicyListEntry
- type PolicyRevision
- type PolicyRevisions
- type Principal
- type PrincipalsService
- type RequiredRecipeService
- type Response
- type Role
- type RolesService
- func (s *RolesService) Create(ctx context.Context, r *Role) (*Response, error)
- func (s *RolesService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *RolesService) EnvironmentRunList(ctx context.Context, role, env string) ([]string, *Response, error)
- func (s *RolesService) Environments(ctx context.Context, role string) ([]string, *Response, error)
- func (s *RolesService) Get(ctx context.Context, name string) (*Role, *Response, error)
- func (s *RolesService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *RolesService) Update(ctx context.Context, r *Role) (*Role, *Response, error)
- type SearchOption
- type SearchResult
- type SearchService
- func (s *SearchService) All(ctx context.Context, index, query string, opts ...SearchOption) iter.Seq2[json.RawMessage, error]
- func (s *SearchService) Indexes(ctx context.Context) (map[string]string, *Response, error)
- func (s *SearchService) Query(ctx context.Context, index, query string, opts ...SearchOption) (*SearchResult, *Response, error)
- func (s *SearchService) SearchAll(ctx context.Context, index, query string, opts ...SearchOption) ([]json.RawMessage, error)
- type ServerStatus
- type SourceKind
- type Stat
- type StatMetric
- type StatsService
- type StatusService
- type Universe
- type UniverseEntry
- type UniverseService
- type User
- type UserCreateResult
- type UsersService
- func (s *UsersService) Authenticate(ctx context.Context, username, password string) (*Response, error)
- func (s *UsersService) Create(ctx context.Context, u *User) (*UserCreateResult, *Response, error)
- func (s *UsersService) Delete(ctx context.Context, name string) (*Response, error)
- func (s *UsersService) Get(ctx context.Context, name string) (*User, *Response, error)
- func (s *UsersService) List(ctx context.Context) (map[string]string, *Response, error)
- func (s *UsersService) Update(ctx context.Context, u *User) (*User, *Response, error)
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotEncrypted means a value (or item) is not a well-formed // encryption wrapper — typically the item simply isn't encrypted. ErrNotEncrypted = errors.New("cinc: data bag item is not encrypted") // ErrDataBagAuth means decryption failed authentication: a wrong // secret, a tampered ciphertext, or a bad v2 HMAC. ErrDataBagAuth = errors.New("cinc: data bag item failed authentication (wrong secret or tampered data)") )
Sentinel errors for encrypted data bag handling, for use with errors.Is.
var ( ErrNotFound = errors.New("cinc: not found") ErrConflict = errors.New("cinc: conflict") ErrForbidden = errors.New("cinc: forbidden") )
Sentinel errors for use with errors.Is.
var ACLPerms = []string{"create", "read", "update", "delete", "grant"}
ACLPerms are the five standard Chef permissions, in the order Chef lists them. The pseudo-permission "all" expands to this whole set.
Functions ¶
func ExpandPerm ¶
ExpandPerm turns a permission argument into the concrete permissions it targets: "all" expands to every standard permission; a single valid permission returns just itself; anything else is an error.
func GenerateKeyPair ¶
GenerateKeyPair generates a 2048-bit RSA key pair and returns it PEM-encoded: the private key as PKCS#1 ("RSA PRIVATE KEY") and the public key as PKIX ("PUBLIC KEY"). It is the generation counterpart to ParseKey/LoadKeyFile, used to mint a new client identity — for example, registering a node's client by handing the server the public key while keeping the private key.
func LoadKeyFile ¶
func LoadKeyFile(path string) (*rsa.PrivateKey, error)
LoadKeyFile reads and parses an RSA private key from a file path.
func ParseKey ¶
func ParseKey(pemBytes []byte) (*rsa.PrivateKey, error)
ParseKey parses a PEM-encoded RSA private key (PKCS#1 or PKCS#8).
func ParseServerURL ¶
ParseServerURL splits a Chef/CINC Server URL of the form https://host[:port]/organizations/<org> into its base server URL (scheme://host[:port]) and organization name.
It is the parsing counterpart to NewClient, which takes the base ServerURL and Org separately: callers that hold a single combined URL (as Chef's credentials files and CHEF_SERVER_URL store it) use this to derive the two.
Types ¶
type ACE ¶
ACE is a single access-control entry: the actors (users/clients by name) and groups granted one permission on one object.
func (*ACE) AddMembers ¶
AddMembers adds each actor and group to the ACE in place, skipping any that are already present, and reports whether the ACE changed. It is the "grant" half of an ACL read-modify-write.
func (*ACE) RemoveMembers ¶
RemoveMembers removes each actor and group from the ACE in place, ignoring any that are absent, and reports whether the ACE changed. It is the "revoke" half of an ACL read-modify-write.
type ACL ¶
type ACL struct {
Create ACE `json:"create"`
Read ACE `json:"read"`
Update ACE `json:"update"`
Delete ACE `json:"delete"`
Grant ACE `json:"grant"`
}
ACL is the complete permission set for a Chef object — five ACEs, one per standard Chef permission: create, read, update, delete, grant.
type ACLsService ¶
type ACLsService struct {
// contains filtered or unexported fields
}
ACLsService accesses the per-object ACL endpoints. Every Chef object that has identity (nodes, clients, groups, containers, cookbooks, data_bags, environments, policies, policy_groups, roles, ...) exposes an _acl subresource at the same path shape, so the object kind is a string.
func (*ACLsService) Get ¶
Get returns the full five-permission ACL of one object.
objectType is the URL segment that identifies the kind ("nodes", "clients", "groups", "containers", "cookbooks", "data", "environments", "policies", "policy_groups", "roles", ...).
func (*ACLsService) GetOrg ¶
GetOrg returns the ACL of the organization object itself, served at /organizations/ORG/organizations/_acl.
func (*ACLsService) GetUser ¶
GetUser returns the ACL of a global user object. User ACLs are top-level (/users/USER/_acl), not org-scoped.
func (*ACLsService) SetOrgPermission ¶
SetOrgPermission rewrites one permission's ACE on the organization object, at /organizations/ORG/organizations/_acl/PERM.
func (*ACLsService) SetPermission ¶
func (s *ACLsService) SetPermission(ctx context.Context, objectType, name, perm string, ace *ACE) error
SetPermission rewrites one permission's ACE on one object. The Chef API requires the request body to wrap the new ACE under the permission name, e.g. {"update":{"actors":[],"groups":["admins"]}}.
perm must be one of the five standard permissions. The pseudo-permission "all" is rejected: it has no endpoint, so callers expand it with ExpandPerm and set each resulting permission.
Nil Actors/Groups slices are coerced to empty arrays so the server does not reject the request for a null member list.
func (*ACLsService) SetUserPermission ¶
SetUserPermission rewrites one permission's ACE on a global user object.
type APIClient ¶
type APIClient struct {
Name string `json:"name"`
Validator bool `json:"validator"`
// PublicKey, if set on Create, registers this PEM public key as the
// client's "default" key instead of having the server generate a keypair.
// Only Create sends it; Update does not, because the server rejects key
// fields on update — manage keys with Keys.Client(name).
PublicKey string `json:"public_key,omitempty"`
// ChefKey is populated only on the Create response. It is never sent.
ChefKey ChefKey `json:"chef_key,omitzero"`
}
APIClient is a Chef API client (node or validator identity). It is named APIClient to avoid colliding with the package's own Client type.
type AssociationsService ¶
type AssociationsService struct {
// contains filtered or unexported fields
}
AssociationsService manages the link between users and organizations: membership at /organizations/ORG/users (distinct from the top-level /users handled by UsersService) and invitations at the org-side /organizations/ORG/association_requests and the user-side /users/USER/association_requests.
func (*AssociationsService) AddMember ¶
AddMember immediately associates an existing user with the organization. This is a superuser-only operation; most callers should use Invite instead.
func (*AssociationsService) GetMember ¶
func (s *AssociationsService) GetMember(ctx context.Context, name string) (*OrgUser, *Response, error)
GetMember returns one organization member's record.
func (*AssociationsService) Invite ¶
func (s *AssociationsService) Invite(ctx context.Context, username string) (*InviteResult, *Response, error)
Invite creates an invitation for username to join the organization.
func (*AssociationsService) ListInvites ¶
func (s *AssociationsService) ListInvites(ctx context.Context) ([]Invitation, *Response, error)
ListInvites returns the organization's pending invitations.
func (*AssociationsService) ListMembers ¶
ListMembers returns the usernames of every user associated with the org.
func (*AssociationsService) ListUserInvites ¶
func (s *AssociationsService) ListUserInvites(ctx context.Context, username string) ([]Invitation, *Response, error)
ListUserInvites returns the invitations pending for the named global user. This is the user-side view at /users/USER/association_requests, so the invitations carry OrgName rather than Username.
func (*AssociationsService) ListUserOrgs ¶
func (s *AssociationsService) ListUserOrgs(ctx context.Context, username string) ([]Org, *Response, error)
ListUserOrgs returns the organizations the named global user belongs to.
func (*AssociationsService) RemoveMember ¶
func (s *AssociationsService) RemoveMember(ctx context.Context, name string) (*OrgUser, *Response, error)
RemoveMember removes a user's association with the organization and returns the user's end state.
func (*AssociationsService) RescindInvite ¶
RescindInvite cancels a pending organization invitation by its ID.
func (*AssociationsService) RespondInvite ¶
func (s *AssociationsService) RespondInvite(ctx context.Context, username, id string, accept bool) (*Response, error)
RespondInvite accepts (accept=true) or rejects (accept=false) one of the user's pending invitations.
func (*AssociationsService) UserInviteCount ¶
func (s *AssociationsService) UserInviteCount(ctx context.Context, username string) (int, *Response, error)
UserInviteCount returns the number of invitations pending for the user.
type Attributes ¶
Attributes is a free-form Chef attribute tree. It marshals as a plain JSON object and preserves any keys it does not interpret.
func (Attributes) Dig ¶
func (a Attributes) Dig(path ...string) (any, bool)
Dig walks nested maps along path and returns the value at the leaf.
It traverses both map[string]any (what encoding/json produces) and Attributes (what a tree built in Go holds).
func (Attributes) GetString ¶
func (a Attributes) GetString(path ...string) string
GetString returns the string at path, or "" if absent or not a string.
type ChefKey ¶
type ChefKey struct {
Name string `json:"name,omitempty"`
PublicKey string `json:"public_key,omitempty"`
PrivateKey string `json:"private_key,omitempty"`
ExpiresAt string `json:"expiration_date,omitempty"`
}
ChefKey holds key material returned when a client is created.
type Chefignore ¶
type Chefignore struct {
// contains filtered or unexported fields
}
Chefignore holds the glob patterns parsed from a `chefignore` file and reports whether a cookbook-relative path should be excluded from upload or packaging. It mirrors Chef::Cookbook::Chefignore: cookbook uploads, cookbook archives, and Policyfile content-identifier computation all match files through one Chefignore so they agree on exactly which files belong to a cookbook.
func LoadChefignore ¶
func LoadChefignore(cookbookDir string) (*Chefignore, error)
LoadChefignore finds the chefignore that applies to cookbookDir and returns its parsed patterns. Like Chef, it looks in cookbookDir first and then in each parent directory up to the filesystem root, using the first file named `chefignore` it finds; files are never merged. That covers both a standalone cookbook and a chef-repo, whose single chefignore lives in `cookbooks/`.
Finding no chefignore is not an error — the returned Chefignore ignores nothing, as it does when the first `chefignore` found is not a regular file.
func (*Chefignore) Ignores ¶
func (c *Chefignore) Ignores(relPath string) bool
Ignores reports whether relPath — a forward-slash, cookbook-relative file path — is excluded by any chefignore pattern. It matches Chef exactly: each pattern is tested against the whole relative path with Ruby's File.fnmatch? and no flags. So `*` and `?` also match "/" (`spec/*` excludes everything under spec/, `*.bak` excludes a .bak file at any depth), a wildcard never matches a leading "." of the path, and a pattern is never tested against a basename or an ancestor directory on its own (`Vagrantfile` excludes only the root Vagrantfile, not files/default/Vagrantfile).
A nil receiver, no patterns, or an empty/"." path all ignore nothing.
func (*Chefignore) Patterns ¶
func (c *Chefignore) Patterns() []string
Patterns returns the chefignore globs, in file order. The result is a copy; mutating it does not affect the Chefignore.
type Client ¶
type Client struct {
// Services.
Nodes *NodesService
Roles *RolesService
Environments *EnvironmentsService
Clients *ClientsService
DataBags *DataBagsService
Search *SearchService
Cookbooks *CookbooksService
CookbookArtifacts *CookbookArtifactsService
Keys *KeysService
Groups *GroupsService
Status *StatusService
License *LicenseService
Policies *PoliciesService
PolicyGroups *PolicyGroupsService
Orgs *OrgsService
Users *UsersService
Containers *ContainersService
ACLs *ACLsService
RequiredRecipe *RequiredRecipeService
Associations *AssociationsService
Principals *PrincipalsService
Universe *UniverseService
Stats *StatsService
// contains filtered or unexported fields
}
Client is a Chef/CINC Server API client. It is safe for concurrent use.
type ClientsService ¶
type ClientsService struct {
// contains filtered or unexported fields
}
ClientsService accesses the /clients endpoints.
func (*ClientsService) Create ¶
Create creates a new client. Unless cl.PublicKey is set, the server generates the client's "default" keypair and the result's ChefKey.PrivateKey carries the private half — the only chance to capture it.
func (*ClientsService) Reregister ¶
Reregister regenerates the named client's "default" key, invalidating the old private key and returning the new one (in the result's PrivateKey).
The keys API has no in-place regenerate, so this deletes the existing "default" key and creates a fresh one with the server generating the pair. A client with no default key (the delete 404s) simply gets one created. The two calls are not atomic: if the create fails after the delete, the client is briefly left without a default key, and the returned error says so — recover by adding a key with Keys.Client(name).Create.
type Config ¶
type Config struct {
ServerURL string // e.g. https://chef.example.com
Org string // organization short name
ClientName string // Chef client or user name
Key *rsa.PrivateKey // RSA private key for request signing
}
Config holds the required parameters for constructing a Client.
type Container ¶
type Container struct {
Name string `json:"containername,omitempty"`
Path string `json:"containerpath,omitempty"`
}
Container is an ACL container — a grouping object that owns the "create" permission for new objects of one kind (nodes, clients, etc.). Chef returns containername and containerpath; they are almost always the same value, but the wire shape uses both keys.
type ContainersService ¶
type ContainersService struct {
// contains filtered or unexported fields
}
ContainersService accesses the /containers endpoints.
func (*ContainersService) Create ¶
Create creates a new container. The Chef Server uses the same value for containername and containerpath, so a single name argument suffices.
type Cookbook ¶
type Cookbook struct {
CookbookName string `json:"cookbook_name"`
Name string `json:"name"`
Version string `json:"version"`
// Metadata is the cookbook's compiled metadata (description, maintainer,
// license, dependencies, …), returned by the server alongside the file
// manifest. omitzero keeps an empty block out of any re-encoded manifest,
// since omitempty does not elide a zero-valued nested struct.
Metadata CookbookMetadata `json:"metadata,omitzero"`
// AllFilesManifest is the flat "all_files" file list. Cookbooks uploaded by
// this client use it, and modern servers return it on Get.
AllFilesManifest []CookbookFileRef `json:"all_files,omitempty"`
// Per-segment slices (classic cookbook_version layout).
Files []CookbookFileRef `json:"files"`
Definitions []CookbookFileRef `json:"definitions"`
Libraries []CookbookFileRef `json:"libraries"`
Attributes []CookbookFileRef `json:"attributes"`
Recipes []CookbookFileRef `json:"recipes"`
Providers []CookbookFileRef `json:"providers"`
Resources []CookbookFileRef `json:"resources"`
RootFiles []CookbookFileRef `json:"root_files"`
Templates []CookbookFileRef `json:"templates"`
}
Cookbook is a single cookbook version's manifest as returned by the server. A server returns files in one of two shapes: the per-segment slices (the classic cookbook_version layout) or the flat AllFilesManifest ("all_files", used by Policyfile-era cookbook and cookbook_artifact manifests). AllFiles merges whichever the server populated.
func (*Cookbook) AllFiles ¶
func (cb *Cookbook) AllFiles() []CookbookFileRef
AllFiles flattens the flat all_files manifest and all nine per-segment slices into a single slice, deduplicated by path.
Most servers populate one shape or the other, but nothing guarantees it, and a file listed in both must still yield one entry: callers turn each entry into work (Download turns it into a file to fetch and write), so a duplicate means two writers for one path. The all_files entry wins, and within the per-segment slices the first occurrence does.
type CookbookArtifactListEntry ¶
type CookbookArtifactListEntry struct {
URL string `json:"url"`
Versions []CookbookArtifactVersion `json:"versions"`
}
CookbookArtifactListEntry is the list response value for one artifact name.
type CookbookArtifactVersion ¶
type CookbookArtifactVersion struct {
Identifier string `json:"identifier"`
URL string `json:"url"`
}
CookbookArtifactVersion is one identifier entry in an artifact list.
type CookbookArtifactsService ¶
type CookbookArtifactsService struct {
// contains filtered or unexported fields
}
CookbookArtifactsService accesses the /cookbook_artifacts endpoints. These are the Policyfile-mode, content-addressed cookbook variant.
func (*CookbookArtifactsService) Delete ¶
func (s *CookbookArtifactsService) Delete(ctx context.Context, name, identifier string) (*Response, error)
Delete removes a single cookbook artifact.
func (*CookbookArtifactsService) Get ¶
func (s *CookbookArtifactsService) Get(ctx context.Context, name, identifier string) (*Cookbook, *Response, error)
Get retrieves a single cookbook artifact by name and identifier.
func (*CookbookArtifactsService) GetVersions ¶
func (s *CookbookArtifactsService) GetVersions(ctx context.Context, name string) (*CookbookArtifactListEntry, *Response, error)
GetVersions returns the available identifiers of a single cookbook artifact (GET /cookbook_artifacts/NAME), unwrapped from the server's single-key {name: {url, versions}} envelope.
func (*CookbookArtifactsService) List ¶
func (s *CookbookArtifactsService) List(ctx context.Context) (map[string]CookbookArtifactListEntry, *Response, error)
List returns all cookbook artifacts and their identifiers.
func (*CookbookArtifactsService) Upload ¶
func (s *CookbookArtifactsService) Upload(ctx context.Context, cb *LocalCookbook, identifier string) error
Upload uploads a LocalCookbook as a cookbook artifact using the sandbox/checksum protocol, then PUTs the artifact manifest at PUT /organizations/NAME/cookbook_artifacts/NAME/IDENTIFIER.
type CookbookFileRef ¶
type CookbookFileRef struct {
Name string `json:"name"`
Path string `json:"path"`
Specificity string `json:"specificity"`
Checksum string `json:"checksum"`
URL string `json:"url"`
}
CookbookFileRef is one file reference in a cookbook version manifest.
type CookbookListEntry ¶
type CookbookListEntry struct {
URL string `json:"url"`
Versions []CookbookVersion `json:"versions"`
}
CookbookListEntry is the list response value for one cookbook name.
type CookbookLock ¶
type CookbookLock struct {
Version string `json:"version,omitempty"`
Identifier string `json:"identifier,omitempty"`
DottedDecimalIdentifier string `json:"dotted_decimal_identifier,omitempty"`
Source string `json:"source,omitempty"`
CacheKey string `json:"cache_key,omitempty"`
SCMInfo json.RawMessage `json:"scm_info,omitempty"`
SourceOptions map[string]any `json:"source_options,omitempty"`
}
CookbookLock is a single cookbook pinning inside a PolicyRevision.
func (CookbookLock) Origin ¶
func (l CookbookLock) Origin() (SourceKind, string, error)
Origin reports how the locked cookbook is sourced and the associated location — a filesystem path, a git URL, an artifactserver URL, or a chef server URL — read from source_options. When more than one source key is present they are preferred in the order path, artifactserver, git, chef_server. It returns an error if no recognized source key is present or its value is not a string.
func (CookbookLock) PinnedVersion ¶
func (l CookbookLock) PinnedVersion() string
PinnedVersion returns the version the lock pins: the source_options "version" when present and non-empty, otherwise the lock's top-level Version.
type CookbookMetadata ¶
type CookbookMetadata struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Description string `json:"description,omitempty"`
LongDescription string `json:"long_description,omitempty"`
Maintainer string `json:"maintainer,omitempty"`
MaintainerEmail string `json:"maintainer_email,omitempty"`
License string `json:"license,omitempty"`
SourceURL string `json:"source_url,omitempty"`
IssuesURL string `json:"issues_url,omitempty"`
Privacy bool `json:"privacy,omitempty"`
// Constraint maps: key -> version constraint string (e.g. ">= 1.0.0").
Dependencies map[string]string `json:"dependencies,omitempty"`
Platforms map[string]string `json:"platforms,omitempty"`
Providing map[string]string `json:"providing,omitempty"`
// Recipes maps a recipe name to its human description.
Recipes map[string]string `json:"recipes,omitempty"`
// Attributes and Groupings are free-form nested structures kept as-is so
// no information is lost; their inner shape is cookbook-defined.
Attributes map[string]any `json:"attributes,omitempty"`
Groupings map[string]any `json:"groupings,omitempty"`
// Version-constraint lists, each an array of constraint tokens
// (e.g. [[">= 13.0", "< 19.0"]] for chef_versions).
ChefVersions [][]string `json:"chef_versions,omitempty"`
OhaiVersions [][]string `json:"ohai_versions,omitempty"`
Gems [][]string `json:"gems,omitempty"`
// EagerLoadLibraries is true, false, or a glob string/list naming the
// libraries chef-client loads eagerly; nil leaves Chef's default (true).
EagerLoadLibraries any `json:"eager_load_libraries,omitempty"`
}
CookbookMetadata is the cookbook's metadata block, as compiled from its metadata.rb/metadata.json and returned inside a cookbook version manifest. Every field is optional — older cookbooks and trimmed server responses may populate only some of them.
type CookbookVersion ¶
CookbookVersion is one version entry in a cookbook list.
type CookbooksService ¶
type CookbooksService struct {
// contains filtered or unexported fields
}
CookbooksService accesses the /cookbooks endpoints.
func (*CookbooksService) Download ¶
func (s *CookbooksService) Download(ctx context.Context, name, version, destDir string) error
Download fetches a cookbook version manifest and writes every file in all nine segments to destDir, recreating the path hierarchy. version may be the literal string "_latest". File content is fetched from pre-signed bookshelf URLs using a plain (unsigned) HTTP GET, matching the upload path in sandboxes.go. Each file is verified against the manifest's MD5 checksum and written atomically; files already in destDir with a matching checksum are skipped.
func (*CookbooksService) Get ¶
func (s *CookbooksService) Get(ctx context.Context, name, version string) (*Cookbook, *Response, error)
Get retrieves a single cookbook version manifest.
func (*CookbooksService) GetVersions ¶
func (s *CookbooksService) GetVersions(ctx context.Context, name, numVersions string) (*CookbookListEntry, *Response, error)
GetVersions returns the available versions of a single cookbook (GET /cookbooks/NAME), unwrapped from the server's single-key {name: {url, versions}} envelope. numVersions limits the versions returned ("" for the server default of one, "all" for every version, or "n"); versions come back newest-first.
func (*CookbooksService) List ¶
func (s *CookbooksService) List(ctx context.Context) (map[string]CookbookListEntry, *Response, error)
List returns all cookbooks and their available versions.
func (*CookbooksService) ListLatest ¶
ListLatest returns the name->URL index of the latest version of each cookbook (GET /cookbooks/_latest).
func (*CookbooksService) ListRecipes ¶
ListRecipes returns every recipe in the latest version of each cookbook (GET /cookbooks/_recipes).
func (*CookbooksService) Upload ¶
func (s *CookbooksService) Upload(ctx context.Context, cb *LocalCookbook) error
Upload uploads a LocalCookbook: sandbox -> file PUTs -> version manifest PUT.
type DataBagItem ¶
DataBagItem is a single data bag item. It must contain an "id" key.
func (DataBagItem) Decrypt ¶
func (i DataBagItem) Decrypt(secret []byte) (DataBagItem, error)
Decrypt returns a new DataBagItem in which "id" is copied verbatim and every other top-level value is treated as an encryption wrapper and decrypted. It reads wrapper versions 1, 2, and 3. The receiver is not modified.
Plaintext "chef_type" and "data_bag" values (added by a Chef Server to the items it echoes back) are dropped rather than rejected, as Chef does; an encrypted value under either name is decrypted like any other.
A value that is not a valid wrapper yields an ErrNotEncrypted error (so a caller can distinguish "this item isn't encrypted"); a failed authentication (wrong secret, tampering, bad HMAC) yields an ErrDataBagAuth error.
func (DataBagItem) Encrypt ¶
func (i DataBagItem) Encrypt(secret []byte) (DataBagItem, error)
Encrypt returns a new DataBagItem in which the "id" value is copied verbatim (in cleartext) and every other top-level value is replaced by a version-3 (AES-256-GCM) encrypted wrapper. The receiver is not modified. It returns an error if the item has no non-empty string "id".
func (DataBagItem) IsEncrypted ¶
func (i DataBagItem) IsEncrypted() bool
IsEncrypted reports whether every non-"id" top-level value is a well-formed encryption wrapper. An empty item, or one containing only "id", is not considered encrypted. Plaintext "chef_type" and "data_bag" values, which a Chef Server adds to the items it echoes back, are ignored, as Chef does.
type DataBagItemsService ¶
type DataBagItemsService struct {
// contains filtered or unexported fields
}
DataBagItemsService accesses the items within a single data bag.
func (*DataBagItemsService) Create ¶
func (s *DataBagItemsService) Create(ctx context.Context, item DataBagItem) (DataBagItem, *Response, error)
Create adds a new item to the bag. The item must contain an "id".
func (*DataBagItemsService) Get ¶
func (s *DataBagItemsService) Get(ctx context.Context, id string) (DataBagItem, *Response, error)
Get retrieves a data bag item by id.
func (*DataBagItemsService) Update ¶
func (s *DataBagItemsService) Update(ctx context.Context, item DataBagItem) (DataBagItem, *Response, error)
Update replaces an existing item.
type DataBagsService ¶
type DataBagsService struct {
// contains filtered or unexported fields
}
DataBagsService accesses the /data endpoints.
func (*DataBagsService) Items ¶
func (s *DataBagsService) Items(bag string) *DataBagItemsService
Items returns a handle to the items of one data bag.
type Environment ¶
type Environment struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
CookbookVersions map[string]string `json:"cookbook_versions,omitempty"`
DefaultAttributes Attributes `json:"default_attributes,omitempty"`
OverrideAttributes Attributes `json:"override_attributes,omitempty"`
}
Environment is a Chef environment object.
type EnvironmentsService ¶
type EnvironmentsService struct {
// contains filtered or unexported fields
}
EnvironmentsService accesses the /environments endpoints.
func (*EnvironmentsService) CookbookVersions ¶
func (s *EnvironmentsService) CookbookVersions(ctx context.Context, env string, runList []string) (map[string]Cookbook, *Response, error)
CookbookVersions solves the given run list against the environment and returns the cookbook versions (including dependencies) required to satisfy it, keyed by cookbook name.
func (*EnvironmentsService) Create ¶
func (s *EnvironmentsService) Create(ctx context.Context, e *Environment) (*Response, error)
Create creates a new environment.
The Chef Server answers POST /environments with {"uri":...} rather than the created object, so there is nothing to return but the response and any error.
func (*EnvironmentsService) Get ¶
func (s *EnvironmentsService) Get(ctx context.Context, name string) (*Environment, *Response, error)
Get retrieves an environment by name.
func (*EnvironmentsService) GetCookbook ¶
func (s *EnvironmentsService) GetCookbook(ctx context.Context, env, name, numVersions string) (map[string]CookbookListEntry, *Response, error)
GetCookbook returns the versions of one cookbook available to the environment, filtered by the environment's version constraints.
func (*EnvironmentsService) ListCookbooks ¶
func (s *EnvironmentsService) ListCookbooks(ctx context.Context, env, numVersions string) (map[string]CookbookListEntry, *Response, error)
ListCookbooks returns the cookbooks (and versions) available to the environment, keyed by cookbook name. numVersions limits the versions per cookbook ("" for the server default, "all" for every version, or "n").
func (*EnvironmentsService) ListNodes ¶
func (s *EnvironmentsService) ListNodes(ctx context.Context, env string) (map[string]string, *Response, error)
ListNodes returns the name->URL index of nodes in the environment.
func (*EnvironmentsService) ListRecipes ¶
func (s *EnvironmentsService) ListRecipes(ctx context.Context, env string) ([]string, *Response, error)
ListRecipes returns the recipes available to the environment.
func (*EnvironmentsService) RoleRunList ¶
func (s *EnvironmentsService) RoleRunList(ctx context.Context, env, role string) ([]string, *Response, error)
RoleRunList returns the role's run list as scoped to the environment: the role's env_run_lists[env], or its default run_list for the _default environment.
func (*EnvironmentsService) Update ¶
func (s *EnvironmentsService) Update(ctx context.Context, e *Environment) (*Environment, *Response, error)
Update replaces an existing environment.
type ErrorResponse ¶
type ErrorResponse struct {
Method string // request method
Path string // request path
StatusCode int // HTTP status code
Messages []string // server-reported error messages
}
ErrorResponse describes a non-2xx response from the Chef server.
func (*ErrorResponse) Error ¶
func (e *ErrorResponse) Error() string
func (*ErrorResponse) Unwrap ¶
func (e *ErrorResponse) Unwrap() error
Unwrap maps the status code to a sentinel error for errors.Is.
type Group ¶
type Group struct {
Name string `json:"name,omitempty"`
GroupName string `json:"groupname,omitempty"`
OrgName string `json:"orgname,omitempty"`
Users []string `json:"users,omitempty"`
Clients []string `json:"clients,omitempty"`
Groups []string `json:"groups,omitempty"`
}
Group is a Chef ACL group. The shape mirrors the server's GET response. On Update the Users/Clients/Groups slices are rewrapped into the nested "actors" object the server requires on PUT.
type GroupsService ¶
type GroupsService struct {
// contains filtered or unexported fields
}
GroupsService accesses the /groups endpoints.
func (*GroupsService) Create ¶
Create creates an empty group with the given name. Use Update to populate its members. The server identifies the new group by "groupname" (a "name" key is rejected with a 400).
func (*GroupsService) Update ¶
Update replaces a group's members. The path segment is the group's name, taken from Name or, when that is empty, GroupName; the body is emitted in the {groupname, actors:{users,clients,groups}} shape the server requires on PUT. Nil member slices become empty JSON arrays rather than null.
A group with neither field set is an error rather than a PUT to the collection endpoint.
type Invitation ¶
type Invitation struct {
ID string `json:"id,omitempty"`
Username string `json:"username,omitempty"`
OrgName string `json:"orgname,omitempty"`
}
Invitation is a pending organization invitation (association request). The org-side listing populates ID and Username; the user-side listing populates ID and OrgName.
type InviteResult ¶
type InviteResult struct {
URI string `json:"uri,omitempty"`
}
InviteResult is the response from creating an organization invitation.
type Key ¶
type Key struct {
Name string `json:"name,omitempty"`
PublicKey string `json:"public_key,omitempty"`
ExpirationDate string `json:"expiration_date,omitempty"` // "infinity" or ISO-8601 UTC
// CreateKey, when true on a create request, asks the server to generate
// the keypair. The response will then carry PrivateKey.
CreateKey bool `json:"create_key,omitempty"`
// PrivateKey is populated only on the response to a server-generated
// create. It is never sent on a request.
PrivateKey string `json:"private_key,omitempty"`
// URI is populated by list and create responses.
URI string `json:"uri,omitempty"`
// Expired is populated by list responses.
Expired bool `json:"expired,omitempty"`
}
Key is one entry in the Chef Server keys API. The same struct serves as the GET response, the create/update request body, and the create response. Most fields are populated in only a subset of those contexts — they are tagged omitempty so requests stay minimal.
type KeyScope ¶
type KeyScope struct {
// contains filtered or unexported fields
}
KeyScope is a handle to one collection of keys (either a user's or a client's). Its CRUD methods all operate against that collection.
func (*KeyScope) Create ¶
Create adds a new key. Set k.CreateKey to have the server generate the keypair; the response's PrivateKey will then be set.
type KeygenStatus ¶
type KeygenStatus struct {
Keys int `json:"keys"`
Max int `json:"max"`
MaxWorkers int `json:"max_workers"`
CurMaxWorkers int `json:"cur_max_workers"`
Inflight int `json:"inflight"`
AvgCreationTimeMS float64 `json:"avg_creation_time_in_ms"`
}
KeygenStatus reports on the server's pre-generated keypair pool.
type KeysService ¶
type KeysService struct {
// contains filtered or unexported fields
}
KeysService is the entry point for the Chef Server keys API. The same API shape is reachable via two different paths: per-user at /users/USER/keys (not org-scoped) and per-client at /organizations/ORG/clients/CLIENT/keys. User and Client return scoped handles for each.
func (*KeysService) Client ¶
func (s *KeysService) Client(name string) *KeyScope
Client returns a handle to the keys of the named org client.
func (*KeysService) User ¶
func (s *KeysService) User(name string) *KeyScope
User returns a handle to the keys of the named global user.
type License ¶
type License struct {
LimitExceeded bool `json:"limit_exceeded"`
NodeLicense int `json:"node_license"`
NodeCount int `json:"node_count"`
UpgradeURL string `json:"upgrade_url,omitempty"`
}
License is the response from GET /license. It reports node-license usage for the Chef Server installation.
type LicenseService ¶
type LicenseService struct {
// contains filtered or unexported fields
}
LicenseService accesses the top-level /license endpoint.
type LocalCookbook ¶
type LocalCookbook struct {
Name string
Version string
Identifier string // set for cookbook artifact uploads
// Metadata is sent as the manifest's metadata block, which Chef Server
// requires and chef-client reads (dependencies, chef_version, …).
// LocalCookbookFromDir fills it from the cookbook's metadata; callers may
// amend it before uploading. Its Name and Version may be left empty — the
// manifest fills them from Name and Version — but if set they must match,
// since the server rejects metadata that disagrees with the URL.
Metadata CookbookMetadata
// contains filtered or unexported fields
}
LocalCookbook is a cookbook assembled from disk, ready to upload. When Identifier is set the manifest is emitted as a cookbook artifact version (chef_type "cookbook_artifact_version") rather than a plain version.
func LocalCookbookFromDir ¶
func LocalCookbookFromDir(dir, version string) (*LocalCookbook, error)
LocalCookbookFromDir walks a cookbook directory into a LocalCookbook ready to pass to CookbooksService.Upload (or, with an identifier, CookbookArtifactsService.Upload). It selects files the way Chef's CookbookVersionLoader does:
- directories at the cookbook root whose names begin with "." (.git, .kitchen, …) are skipped; dotfiles, and dot-directories deeper down, are kept;
- chef-zero's .uploaded-cookbook-version.json is skipped;
- files excluded by the applicable chefignore (see LoadChefignore, which also searches parent directories) are skipped.
Metadata comes from metadata.json when present (complete, as compiled by knife or Berkshelf), and otherwise from a static parse of metadata.rb that recognizes only literal calls — see parseMetadataRb for exactly which. Supply a metadata.json, or amend Metadata on the result, for anything computed in Ruby.
The cookbook name is the metadata's name, falling back to the base name of dir. version is the version to upload as; when empty the metadata's version is used, and failing that Chef's default of "0.0.0". A version that differs from the one the metadata declares is an error, since the server would reject the mismatch. Every remaining regular file is read and checksummed. An empty directory is an error.
type Node ¶
type Node struct {
Name string `json:"name"`
Environment string `json:"chef_environment,omitempty"`
RunList []string `json:"run_list"`
Normal Attributes `json:"normal,omitempty"`
Default Attributes `json:"default,omitempty"`
Override Attributes `json:"override,omitempty"`
Automatic Attributes `json:"automatic,omitempty"`
PolicyName string `json:"policy_name,omitempty"`
PolicyGroup string `json:"policy_group,omitempty"`
}
Node is a Chef node object.
func (*Node) AddRunListItems ¶
AddRunListItems appends run-list entries that are not already present, preserving existing entries and their order.
func (*Node) AddTags ¶
AddTags adds tags that are not already present, preserving the order of the existing tags and appending new ones.
func (*Node) Attribute ¶
Attribute looks up an attribute by name across the node's precedence levels, returning the first match in Chef read-precedence order — automatic → override → normal → default (automatic, the highest precedence, wins). The name may be a dot-separated path into nested attributes (e.g. "network.default_gateway").
func (*Node) AttributeString ¶
AttributeString resolves Attribute and coerces the result to a string: a string is returned as-is, a non-empty array yields its first element (coerced), and any other value is formatted with fmt.Sprint. It returns "" when the attribute is absent. This mirrors how Chef tooling reads a single scalar attribute (e.g. fqdn) that may be stored as a one-element array.
func (Node) MarshalJSON ¶
MarshalJSON encodes the node with run_list always present as an array. Chef's object validator requires an array there, and a nil slice with no omitempty would encode as null.
func (*Node) RemoveRunListItems ¶
RemoveRunListItems removes the given entries from the node's run list.
func (*Node) RemoveTags ¶
RemoveTags drops the given tags from the node.
type NodesService ¶
type NodesService struct {
// contains filtered or unexported fields
}
NodesService accesses the /nodes endpoints.
func (*NodesService) Create ¶
Create creates a new node.
The Chef Server answers POST /nodes with {"uri":...} rather than the created object, so there is nothing to return but the response and any error.
type Option ¶
type Option func(*options)
Option customizes a Client.
func WithChefVersion ¶
WithChefVersion sets the X-Chef-Version header.
func WithHTTPClient ¶
WithHTTPClient sets a custom *http.Client.
func WithMaxRetries ¶
WithMaxRetries sets the retry count for idempotent requests.
func WithSkipTLSVerify ¶
WithSkipTLSVerify disables TLS certificate verification (testing only).
func WithTransferTimeout ¶ added in v0.14.0
WithTransferTimeout bounds each attempt at a cookbook file transfer (the unsigned bookshelf GETs and sandbox PUTs behind Cookbooks.Upload/Download and CookbookArtifacts.Upload), including reading or sending the whole body. It replaces the http.Client's own Timeout for those requests only; API calls keep it. The default is 10 minutes; 0 removes the limit, leaving the request context as the only bound. Negative values are ignored.
type Org ¶
type Org struct {
Name string `json:"name,omitempty"`
FullName string `json:"full_name,omitempty"`
GUID string `json:"guid,omitempty"`
}
Org is the top-level Chef Server organization. These endpoints live at /organizations (not under any one org) and are typically reserved for the pivotal superuser identity.
type OrgCreateResult ¶
type OrgCreateResult struct {
URI string `json:"uri,omitempty"`
ClientName string `json:"clientname,omitempty"`
PrivateKey string `json:"private_key,omitempty"`
}
OrgCreateResult is the response from POST /organizations. The PrivateKey is the generated validator client's RSA key and is returned **only** at creation time — store it before the response is dropped.
type OrgUser ¶
type OrgUser struct {
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
DisplayName string `json:"display_name,omitempty"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
PublicKey string `json:"public_key,omitempty"`
}
OrgUser is an organization member's record as returned by the org-scoped /organizations/ORG/users endpoints. It is a projection of the global user object limited to the fields the membership API returns.
type OrgsService ¶
type OrgsService struct {
// contains filtered or unexported fields
}
OrgsService accesses the top-level /organizations endpoints.
func (*OrgsService) Create ¶
func (s *OrgsService) Create(ctx context.Context, o *Org) (*OrgCreateResult, *Response, error)
Create creates a new organization. The response contains the generated validator client name and its private key — capture the key, it is not retrievable later.
type PoliciesService ¶
type PoliciesService struct {
// contains filtered or unexported fields
}
PoliciesService accesses the /policies endpoints.
func (*PoliciesService) CreateRevision ¶
func (s *PoliciesService) CreateRevision(ctx context.Context, name string, doc any) (*PolicyRevision, *Response, error)
CreateRevision uploads a new revision of a policy. The body is passed through as-is, so callers may supply a *PolicyRevision, a map, or any other JSON-marshallable value matching the Policyfile schema.
func (*PoliciesService) DeleteRevision ¶
func (s *PoliciesService) DeleteRevision(ctx context.Context, name, revisionID string) (*Response, error)
DeleteRevision removes a single revision of a policy.
func (*PoliciesService) Get ¶
func (s *PoliciesService) Get(ctx context.Context, name string) (*PolicyRevisions, *Response, error)
Get returns the set of revisions known for a single policy name.
func (*PoliciesService) GetRevision ¶
func (s *PoliciesService) GetRevision(ctx context.Context, name, revisionID string) (*PolicyRevision, *Response, error)
GetRevision fetches a single revision of a policy.
func (*PoliciesService) List ¶
func (s *PoliciesService) List(ctx context.Context) (map[string]PolicyListEntry, *Response, error)
List returns every policy and its revision ids.
func (*PoliciesService) PushRevision ¶
func (s *PoliciesService) PushRevision(ctx context.Context, lockJSON []byte, group string, cookbooks map[string]*LocalCookbook) (*PolicyRevision, *Response, error)
PushRevision deploys a Policyfile lock to a policy group: it uploads each cookbook the lock pins as a cookbook artifact (under the identifier the lock records), then associates the resulting revision with group. This is the server-side half of `chef push`.
lockJSON is the raw Policyfile.lock.json; it is parsed to discover the policy name and cookbook locks, and sent verbatim to the server so no lock fields are lost. cookbooks maps each cookbook-lock name to the on-disk cookbook to upload for it — callers fetch these from the lock's sources first (see ParsePolicyfileLock).
Chef Server rejects a PUT of an existing artifact identifier with 409, so, like chef-cli, PushRevision lists the server's artifacts once and uploads only the identifiers it lacks; a 409 from a concurrent pusher is treated as already uploaded, since the identifier is a content hash. The artifact uploads and the group association are not atomic, but this makes a failed push safe to retry and lets one lock be pushed to several groups.
type PolicyAssignment ¶
type PolicyAssignment struct {
RevisionID string `json:"revision_id"`
}
PolicyAssignment is the per-policy value inside a PolicyGroup — it pins one policy name to a specific revision id.
type PolicyGroup ¶
type PolicyGroup struct {
URI string `json:"uri,omitempty"`
Policies map[string]PolicyAssignment `json:"policies,omitempty"`
}
PolicyGroup is the response from GET /policy_groups/NAME. The Policies map shows which revision of each policy is currently active in the group.
type PolicyGroupsService ¶
type PolicyGroupsService struct {
// contains filtered or unexported fields
}
PolicyGroupsService accesses the /policy_groups endpoints.
func (*PolicyGroupsService) DeletePolicy ¶
func (s *PolicyGroupsService) DeletePolicy(ctx context.Context, group, policy string) (*Response, error)
DeletePolicy removes the pinning of one policy from a group, without deleting the underlying revision.
func (*PolicyGroupsService) Get ¶
func (s *PolicyGroupsService) Get(ctx context.Context, name string) (*PolicyGroup, *Response, error)
Get returns one group's pinned policy revisions.
func (*PolicyGroupsService) GetPolicy ¶
func (s *PolicyGroupsService) GetPolicy(ctx context.Context, group, policy string) (*PolicyRevision, *Response, error)
GetPolicy returns the policy revision currently active in group for the named policy.
func (*PolicyGroupsService) List ¶
func (s *PolicyGroupsService) List(ctx context.Context) (map[string]PolicyGroup, *Response, error)
List returns every policy group and the policy revisions pinned in it.
func (*PolicyGroupsService) PutPolicy ¶
func (s *PolicyGroupsService) PutPolicy(ctx context.Context, group, policy string, doc any) (*PolicyRevision, *Response, error)
PutPolicy uploads a policy revision and pins it into group as the active revision of policy. This is the primary way to associate a revision with a group, and creates the group implicitly if it does not exist. The doc body may be a *PolicyRevision, a map, or any JSON-marshallable Policyfile.
type PolicyListEntry ¶
type PolicyListEntry struct {
URI string `json:"uri"`
Revisions map[string]json.RawMessage `json:"revisions"`
}
PolicyListEntry is the per-policy value in the /policies index. The Revisions map's keys are revision identifiers; values are intentionally empty objects in the wire format.
type PolicyRevision ¶
type PolicyRevision struct {
RevisionID string `json:"revision_id,omitempty"`
Name string `json:"name,omitempty"`
RunList []string `json:"run_list,omitempty"`
NamedRunLists map[string][]string `json:"named_run_lists,omitempty"`
CookbookLocks map[string]CookbookLock `json:"cookbook_locks,omitempty"`
DefaultAttributes map[string]any `json:"default_attributes,omitempty"`
OverrideAttributes map[string]any `json:"override_attributes,omitempty"`
SolutionDependencies json.RawMessage `json:"solution_dependencies,omitempty"`
IncludedPolicyLocks []json.RawMessage `json:"included_policy_locks,omitempty"`
}
PolicyRevision is a single Policyfile document. The shape mirrors the well-known top-level fields; unknown fields are preserved through the Extra map when round-tripping.
func LoadPolicyfileLock ¶
func LoadPolicyfileLock(path string) (*PolicyRevision, []byte, error)
LoadPolicyfileLock reads and parses a Policyfile.lock.json from disk. It returns the parsed lock alongside the original bytes, which callers pass verbatim to Policies.PushRevision so no lock fields are lost on the round trip.
func ParsePolicyfileLock ¶
func ParsePolicyfileLock(data []byte) (*PolicyRevision, error)
ParsePolicyfileLock unmarshals the bytes of a Policyfile.lock.json into a PolicyRevision, which models the lock's structure (name, run lists, cookbook locks, attributes, solution dependencies). Use it to inspect a lock — for example to discover which cookbooks must be fetched before a push.
To deploy a lock, prefer Policies.PushRevision with the original bytes: a lock can carry fields PolicyRevision does not model (such as a cookbook lock's "origin"), so re-marshalling a parsed value would drop them.
type PolicyRevisions ¶
type PolicyRevisions struct {
Revisions map[string]json.RawMessage `json:"revisions"`
}
PolicyRevisions is the body returned by GET /policies/NAME.
type Principal ¶
type Principal struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"` // "user" or "client"
PublicKey string `json:"public_key,omitempty"`
AuthzID string `json:"authz_id,omitempty"`
OrgMember bool `json:"org_member"`
}
Principal is one identity entry returned by the principals endpoint: the public key and metadata for a user or client. A single name may resolve to more than one principal (e.g. a client and a user sharing a name), which is why the endpoint returns a list.
type PrincipalsService ¶
type PrincipalsService struct {
// contains filtered or unexported fields
}
PrincipalsService accesses /organizations/ORG/principals/NAME, the endpoint used to look up the public key(s) and type of a user or client so that a request's signature can be verified.
type RequiredRecipeService ¶
type RequiredRecipeService struct {
// contains filtered or unexported fields
}
RequiredRecipeService accesses the /required_recipe endpoint. Unlike the rest of the API this endpoint returns a Ruby recipe as text/plain rather than JSON, so it bypasses the generic do[T] helper.
type Response ¶
type Response struct {
HTTPResponse *http.Response // the underlying response (body already closed)
StatusCode int // convenience copy of HTTPResponse.StatusCode
}
Response wraps the raw HTTP response returned by an API call.
type Role ¶
type Role struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
RunList []string `json:"run_list"`
DefaultAttributes Attributes `json:"default_attributes,omitempty"`
OverrideAttributes Attributes `json:"override_attributes,omitempty"`
EnvRunLists map[string][]string `json:"env_run_lists,omitempty"`
}
Role is a Chef role object.
func (Role) MarshalJSON ¶
MarshalJSON encodes the role with run_list always present as an array, for the same reason as Node.MarshalJSON.
type RolesService ¶
type RolesService struct {
// contains filtered or unexported fields
}
RolesService accesses the /roles endpoints.
func (*RolesService) Create ¶
Create creates a new role.
The Chef Server answers POST /roles with {"uri":...} rather than the created object, so there is nothing to return but the response and any error.
func (*RolesService) EnvironmentRunList ¶
func (s *RolesService) EnvironmentRunList(ctx context.Context, role, env string) ([]string, *Response, error)
EnvironmentRunList returns the role's run list for one environment (env_run_lists[env], or the default run_list when env is "_default").
func (*RolesService) Environments ¶
Environments lists the environments for which the role has an environment-specific run list (always including "_default").
type SearchOption ¶
type SearchOption func(*searchParams)
SearchOption customizes a search query.
func WithPartial ¶
func WithPartial(keys map[string][]string) SearchOption
WithPartial requests partial search projection (key -> attribute path).
type SearchResult ¶
type SearchResult struct {
Total int `json:"total"`
Start int `json:"start"`
Rows []json.RawMessage `json:"rows"`
}
SearchResult is one page of search results.
type SearchService ¶
type SearchService struct {
// contains filtered or unexported fields
}
SearchService accesses the /search endpoints.
func (*SearchService) All ¶ added in v0.14.0
func (s *SearchService) All(ctx context.Context, index, query string, opts ...SearchOption) iter.Seq2[json.RawMessage, error]
All returns an iterator over every row matching query, fetching one page at a time so only the current page is held in memory:
for row, err := range c.Search.All(ctx, "node", "*:*") {
if err != nil {
return err
}
// decode row
}
Breaking out of the loop stops further page requests. A failed page request (including ctx cancellation) is yielded once as a nil row with a non-nil error, after which iteration ends. Options and paging behave as in SearchAll.
func (*SearchService) Indexes ¶
Indexes returns the name->URL index of available search indexes (node, role, client, environment, and one per data bag).
func (*SearchService) Query ¶
func (s *SearchService) Query(ctx context.Context, index, query string, opts ...SearchOption) (*SearchResult, *Response, error)
Query runs a single search against index with the given query string.
func (*SearchService) SearchAll ¶
func (s *SearchService) SearchAll(ctx context.Context, index, query string, opts ...SearchOption) ([]json.RawMessage, error)
SearchAll pages through every result, returning all rows. WithStart(n) is respected as the absolute offset of the first row to fetch; subsequent pages advance the offset by the number of rows received per page.
SearchAll holds the whole result set in memory; use All to process rows page by page instead.
type ServerStatus ¶
type ServerStatus struct {
Status string `json:"status"`
Upstreams map[string]string `json:"upstreams,omitempty"`
Keygen KeygenStatus `json:"keygen"`
}
ServerStatus is the response from GET /_status. The endpoint is typically unauthenticated and is used by load balancers as a health probe.
type SourceKind ¶
type SourceKind string
SourceKind identifies how a Policyfile cookbook lock is sourced. The values match the source_options keys Chef writes into a Policyfile.lock.json.
const ( SourcePath SourceKind = "path" SourceArtifactserver SourceKind = "artifactserver" SourceGit SourceKind = "git" SourceChefServer SourceKind = "chef_server" )
The source kinds a cookbook lock can name, one per source_options key.
type Stat ¶
type Stat struct {
Name string `json:"name"`
Type string `json:"type"`
Help string `json:"help"`
Metrics []StatMetric `json:"metrics"`
}
Stat is one metric family reported by the /_stats endpoint.
type StatMetric ¶
type StatMetric struct {
Value string `json:"value"`
Labels map[string]string `json:"labels,omitempty"`
}
StatMetric is one measured value within a Stat, optionally carrying Prometheus-style labels.
type StatsService ¶
type StatsService struct {
// contains filtered or unexported fields
}
StatsService accesses the top-level /_stats endpoint, which reports connection-pool, PostgreSQL, and Erlang VM statistics.
Unlike every other endpoint, /_stats authenticates with HTTP Basic auth (default user "statsuser") rather than the Chef signing protocol, so its requests are NOT Chef-signed.
type StatusService ¶
type StatusService struct {
// contains filtered or unexported fields
}
StatusService accesses the top-level /_status endpoint.
func (*StatusService) Get ¶
func (s *StatusService) Get(ctx context.Context) (*ServerStatus, *Response, error)
Get returns the server's health and keygen pool status.
type Universe ¶
type Universe map[string]map[string]UniverseEntry
Universe is the known collection of cookbooks, keyed by cookbook name and then by version string. It feeds Berkshelf/Supermarket dependency resolution.
type UniverseEntry ¶
type UniverseEntry struct {
LocationPath string `json:"location_path,omitempty"`
LocationType string `json:"location_type,omitempty"`
Dependencies map[string]string `json:"dependencies,omitempty"`
}
UniverseEntry describes one cookbook version in the universe: where to fetch it and what it depends on.
type UniverseService ¶
type UniverseService struct {
// contains filtered or unexported fields
}
UniverseService accesses the /universe endpoint, which exists both org-scoped and at the top level.
type User ¶
type User struct {
UserName string `json:"username,omitempty"`
DisplayName string `json:"display_name,omitempty"`
Email string `json:"email,omitempty"`
FirstName string `json:"first_name,omitempty"`
MiddleName string `json:"middle_name,omitempty"`
LastName string `json:"last_name,omitempty"`
// Password is sent only on create/update; never returned.
Password string `json:"password,omitempty"`
// CreateKey, when true on create, asks the server to generate the user's
// default keypair. The response then carries ChefKey with PrivateKey set.
CreateKey bool `json:"create_key,omitempty"`
// PublicKey may be supplied on create to set the default key without
// having the server generate one. Mutually exclusive with CreateKey.
PublicKey string `json:"public_key,omitempty"`
}
User is a global Chef Server user account. These live at /users (not under any one org) and represent humans who can be added to organizations.
type UserCreateResult ¶
type UserCreateResult struct {
URI string `json:"uri,omitempty"`
ChefKey ChefKey `json:"chef_key"`
}
UserCreateResult is the response from POST /users. The ChefKey.PrivateKey is returned **only** when the user is created with CreateKey=true; capture it before the response is dropped.
type UsersService ¶
type UsersService struct {
// contains filtered or unexported fields
}
UsersService accesses the top-level /users endpoints.
func (*UsersService) Authenticate ¶
func (s *UsersService) Authenticate(ctx context.Context, username, password string) (*Response, error)
Authenticate verifies a user's username and password against the top-level /authenticate_user endpoint. A nil error means the credentials are valid; a 401 is reported as an error wrapping ErrUnauthorized.
func (*UsersService) Create ¶
func (s *UsersService) Create(ctx context.Context, u *User) (*UserCreateResult, *Response, error)
Create creates a new user. With CreateKey=true the response carries the generated private key, which is the only chance to capture it.
Source Files
¶
- acls.go
- associations.go
- attributes.go
- checksum.go
- chefignore.go
- client.go
- clients.go
- containers.go
- cookbook_artifacts.go
- cookbook_metadata.go
- cookbooks.go
- crud.go
- databag_crypto.go
- databags.go
- doc.go
- environments.go
- errors.go
- groups.go
- key.go
- keys.go
- license.go
- nodes.go
- options.go
- orgs.go
- parallel.go
- pathescape.go
- policies.go
- policy_groups.go
- policyfile.go
- principals.go
- required_recipe.go
- response.go
- roles.go
- sandboxes.go
- search.go
- serverurl.go
- stats.go
- status.go
- transport.go
- universe.go
- users.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
cinctest
Package cinctest provides an httptest-based fake Chef server for tests.
|
Package cinctest provides an httptest-based fake Chef server for tests. |
|
signing
Package signing implements the Chef v1.3 (SHA-256) signed-header protocol.
|
Package signing implements the Chef v1.3 (SHA-256) signed-header protocol. |