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 ¶
- Constants
- Variables
- func CompareCookbookVersions(a, b string) int
- func ExpandPerm(perm string) ([]string, error)
- func FormatServerURL(serverURL, org string) string
- func GenerateKeyPair() (privatePEM, publicPEM string, err error)
- func LoadDataBagSecret(path string) ([]byte, error)
- func LoadKeyFile(path string) (*rsa.PrivateKey, error)
- func NormalizeRunList(items []string) []string
- func NormalizeRunListItem(item string) string
- func ParseDataBagSecret(data []byte) ([]byte, error)
- func ParseKey(pemBytes []byte) (*rsa.PrivateKey, error)
- func ParseServerURL(raw string) (serverURL, org string, err error)
- func UnwrapSearchRow(row json.RawMessage) json.RawMessage
- func ValidateRunListItem(item string) error
- type ACE
- type ACL
- type ACLChangeError
- type ACLTarget
- 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) GetTarget(ctx context.Context, t ACLTarget) (*ACL, *Response, error)
- func (s *ACLsService) GetUser(ctx context.Context, name string) (*ACL, *Response, error)
- func (s *ACLsService) Grant(ctx context.Context, t ACLTarget, perm string, actors, groups []string) (changed []string, err error)
- func (s *ACLsService) Revoke(ctx context.Context, t ACLTarget, perm string, actors, groups []string) (changed []string, err 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) SetTargetPermission(ctx context.Context, t ACLTarget, 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) DownloadFiles(ctx context.Context, cb *Cookbook, 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) ListVersions(ctx context.Context, numVersions string) (map[string]CookbookListEntry, *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) CreateEncrypted(ctx context.Context, item DataBagItem, secret []byte) (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) GetDecrypted(ctx context.Context, id string, secret []byte) (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)
- func (s *DataBagItemsService) UpdateEncrypted(ctx context.Context, item DataBagItem, secret []byte) (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) AddMembers(ctx context.Context, group string, kind MemberKind, names ...string) (*MemberChange, error)
- 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) RemoveMembers(ctx context.Context, group string, kind MemberKind, names ...string) (*MemberChange, 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 LocalCookbookFile
- type LocalCookbookOption
- type MemberChange
- type MemberKind
- 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) AttributeScalar(name string) (string, bool)
- func (n *Node) AttributeString(name string) string
- func (n *Node) EnvironmentName() string
- func (n *Node) LastCheckin() (time.Time, bool)
- 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) Modify(ctx context.Context, name string, fn func(*Node) error) (*Node, bool, 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, ...) (*PushResult, *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 PushResult
- 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) DataBagItems(ctx context.Context, bag, query string, opts ...SearchOption) iter.Seq2[DataBagItem, error]
- func (s *SearchService) Indexes(ctx context.Context) (map[string]string, *Response, error)
- func (s *SearchService) Nodes(ctx context.Context, query string, opts ...SearchOption) iter.Seq2[*Node, 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 ServerAPIVersion
- 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) SetPassword(ctx context.Context, name, password string) (*Response, error)
- func (s *UsersService) Update(ctx context.Context, u *User) (*User, *Response, error)
Constants ¶
const ( ACLClients = "clients" ACLContainers = "containers" ACLCookbooks = "cookbooks" ACLCookbookArtifacts = "cookbook_artifacts" ACLDataBags = "data" ACLEnvironments = "environments" ACLGroups = "groups" ACLNodes = "nodes" ACLPolicies = "policies" ACLPolicyGroups = "policy_groups" ACLRoles = "roles" )
Object-type URL segments for the org-scoped objects erchef serves an _acl endpoint on, for use with ObjectACL. Most are the object's collection name; data bags are the exception, served under "data".
const LatestVersion = "_latest"
LatestVersion is the version the Chef Server resolves to the highest version of a cookbook, e.g. Cookbooks.Get(ctx, "nginx", LatestVersion).
const SuperuserName = "pivotal"
SuperuserName is the Chef Server's built-in superuser, "pivotal". Some server-wide operations are reserved to it rather than to any org admin or server-admin: creating organizations, POST /authenticate_user, and associating a user with an org without an invitation. Its key lives on the server (/etc/opscode/pivotal.pem on erchef).
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)") // ErrAlreadyEncrypted means Encrypt was handed an item that already // holds an encrypted value. Encrypting it again would wrap the // ciphertext a second time, and the stored item would then decrypt to // encryption wrappers instead of the plaintext. ErrAlreadyEncrypted = errors.New("cinc: data bag item is already encrypted") )
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") // ErrBadRequest is a 400: the server refused the request as malformed or // naming something that does not exist, such as an unknown actor or group // in an ACL write. ErrBadRequest = errors.New("cinc: bad request") )
Sentinel errors for use with errors.Is.
var ACLObjectTypes = []string{ ACLClients, ACLContainers, ACLCookbooks, ACLCookbookArtifacts, ACLDataBags, ACLEnvironments, ACLGroups, ACLNodes, ACLPolicies, ACLPolicyGroups, ACLRoles, }
ACLObjectTypes lists every object-type segment above, sorted. A cookbook's ACL is shared by all its versions, so it is addressed by name alone, as is a cookbook artifact's and a policy's.
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.
var ErrEmptyDataBagSecret = errors.New("cinc: data bag secret is empty")
ErrEmptyDataBagSecret means an encrypted data bag secret has nothing left once its surrounding whitespace is stripped. Chef refuses such a secret ("invalid zero length secret"), and so do LoadDataBagSecret and ParseDataBagSecret.
var ErrInvalidDataBagSecret = errors.New("cinc: data bag secret is not valid UTF-8, which Chef cannot read")
ErrInvalidDataBagSecret means an encrypted data bag secret is not valid UTF-8. Chef reads the secret as UTF-8 text and cannot use such a file, so LoadDataBagSecret and ParseDataBagSecret refuse it too.
var ErrInvalidRunListItem = errors.New("cinc: invalid run list item")
ErrInvalidRunListItem means a run-list entry is not one a Chef Server accepts; ValidateRunListItem wraps it.
var ErrMetadataVersionNotLiteral = errors.New("version is not a string literal, so it can't be read without running Ruby")
ErrMetadataVersionNotLiteral reports a metadata.rb whose version is set by something other than a string literal (a method call, interpolation, a conditional). Its value can only be known by running the Ruby, which this package never does. ParseMetadataRb returns it, wrapped with the line, alongside the rest of the metadata, whose Version is left empty; without the check the cookbook would silently take Chef's default of 0.0.0.
var ErrMissingDataBagItemID = errors.New("cinc: data bag item requires a non-empty string \"id\"")
ErrMissingDataBagItemID means a data bag item has no "id", or its "id" is not a non-empty string. A Chef Server stores and indexes items by it.
var ErrNoServerAPIVersion = errors.New("cinc: the server did not report which API versions it supports")
ErrNoServerAPIVersion means GET /server_api_version succeeded but reported no API version range, in neither its body nor its X-Ops-Server-API-Version header, as from a proxy or a server that is not a Chef Server.
Functions ¶
func CompareCookbookVersions ¶ added in v0.15.0
CompareCookbookVersions compares two cookbook versions the way Chef does, numerically by major, minor and patch ("x.y" is "x.y.0"), and returns -1, 0 or +1 as a is older than, equal to or newer than b.
A string that is not a valid cookbook version ("x.y" or "x.y.z") is older than every valid one, and two such strings compare as strings, so the ordering is total: sorting with it is deterministic whatever a server sends.
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 FormatServerURL ¶ added in v0.15.0
FormatServerURL joins a base server URL and an organization into the combined https://host[:port]/organizations/<org> form that Chef's credentials files and CHEF_SERVER_URL use. It is the inverse of ParseServerURL: trailing slashes on serverURL are trimmed and org is path-escaped.
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 LoadDataBagSecret ¶ added in v0.15.0
LoadDataBagSecret reads an encrypted data bag secret file the way Chef's EncryptedDataBagItem.load_secret does, so a secret file behaves the same for this package, knife and chef-client. See ParseDataBagSecret for how the contents are interpreted. A read error is returned wrapped (so errors.Is(err, fs.ErrNotExist) works); an empty or non-UTF-8 secret wraps ErrEmptyDataBagSecret or ErrInvalidDataBagSecret and names the file.
Chef's load_secret also accepts a URL ("https://host/secret") and fetches the secret from it. LoadDataBagSecret does not: path is always a local file. Fetch a remote secret yourself and pass it to ParseDataBagSecret.
func LoadKeyFile ¶
func LoadKeyFile(path string) (*rsa.PrivateKey, error)
LoadKeyFile reads and parses an RSA private key from a file path.
func NormalizeRunList ¶ added in v0.15.0
NormalizeRunList returns the run list a Chef Server would store for items: each entry normalized with NormalizeRunListItem, then exact duplicates dropped, keeping the first occurrence and the original order. Semantic duplicates such as "recipe[nginx]" and "recipe[nginx::default]" are kept. The result is never nil, so it encodes as a JSON array, and items is not modified.
This mirrors erchef's chef_object_base:normalize_run_list/1, which erchef applies to a node's run_list (chef_node.erl) and to a role's run_list and each of its env_run_lists (chef_role.erl) on every save.
func NormalizeRunListItem ¶ added in v0.15.0
NormalizeRunListItem returns a run-list entry in the explicit form a Chef Server stores: "role[...]" and "recipe[...]" are returned unchanged, and anything else is taken to be a recipe and wrapped, so "nginx" becomes "recipe[nginx]" and "nginx::server" becomes "recipe[nginx::server]".
This mirrors erchef's chef_object_base:normalize_item/1 (chef-server/src/oc_erchef/apps/chef_objects/src/chef_object_base.erl), which, like this function, assumes the item has already been validated.
func ParseDataBagSecret ¶ added in v0.15.0
ParseDataBagSecret interprets the contents of an encrypted data bag secret file as Chef does (IO.read(path).strip):
- Leading and trailing NUL bytes and ASCII whitespace (space, \t, \n, \v, \f, \r) are removed, as Ruby's String#strip removes them. Inner whitespace, and Unicode whitespace at either end, is kept.
- The contents must be valid UTF-8. Chef reads the file as UTF-8 text and String#strip raises on an invalid byte sequence, so knife and chef-client cannot use such a file. It is refused with ErrInvalidDataBagSecret.
- A secret that is empty once stripped is refused with ErrEmptyDataBagSecret.
The returned bytes are the secret itself (the AES key is derived from them by Encrypt and Decrypt) and never alias data. A secret given literally on a command line, as knife's --secret, is used exactly as given and needs no parsing.
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.
func UnwrapSearchRow ¶ added in v0.15.0
func UnwrapSearchRow(row json.RawMessage) json.RawMessage
UnwrapSearchRow returns the object a search row describes. Search returns two kinds of row that wrap the object in an envelope:
- A partial search row (WithPartial, WithPartialPaths) is an object with exactly two keys, a string "url" and an object "data"; the projection is "data".
- A full search of a data bag index returns each item as a Chef::DataBagItem, {"name": "data_bag_item_<bag>_<id>", "json_class": "Chef::DataBagItem", "chef_type": "data_bag_item", "data_bag": <bag>, "raw_data": {...}}; the item is "raw_data". A row is taken to be one when it has that json_class, that chef_type and an object "raw_data".
Any other row (a full node, role, client or environment, or anything that is not an object) is returned unchanged. Neither test misfires on a real object: every indexed object has more keys than url and data (nodes, roles, clients and environments a name, a data bag item an id), and the server unwraps a Chef::DataBagItem envelope on write, so no stored item keeps one.
func ValidateRunListItem ¶ added in v0.15.1
ValidateRunListItem reports whether item is a run-list entry a Chef Server accepts, so a caller can refuse a malformed one (such as "recipe[") before the server answers the whole save with a 400. As erchef does, it picks the pattern by prefix: "role[NAME]"; "recipe[...]" around a recipe; and anything else is a bare recipe, "COOKBOOK" or "COOKBOOK::RECIPE", either optionally followed by "@VERSION" with two or three numeric parts. Names use only ASCII letters, digits, '_', '-' and '.'. A failure wraps ErrInvalidRunListItem and names the item.
This mirrors erchef's chef_json_validator:valid_run_list_item/1 (chef-server/src/oc_erchef/apps/chef_objects/src/chef_json_validator.erl, with the regexes in chef_regex.erl) and cinc-server-ng's validRunList. NormalizeRunList does not call it; validate entries first when they come from a user.
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 ACLChangeError ¶ added in v0.15.0
type ACLChangeError struct {
Target ACLTarget
Perm string // the permission whose write failed
Changed []string // permissions already written, in ACLPerms order
Err error
}
ACLChangeError reports a Grant or Revoke that stopped part way. The server has no multi-permission write, so each permission is its own PUT: the ones in Changed were applied before the write of Perm failed, and the ones after Perm were not attempted. Err is the server's error, so errors.Is(err, ErrBadRequest) and friends see through it.
func (*ACLChangeError) Error ¶ added in v0.15.0
func (e *ACLChangeError) Error() string
func (*ACLChangeError) Unwrap ¶ added in v0.15.0
func (e *ACLChangeError) Unwrap() error
type ACLTarget ¶ added in v0.15.0
type ACLTarget struct {
// contains filtered or unexported fields
}
ACLTarget identifies the object whose ACL is read or written. Build one with ObjectACL, OrgACL or UserACL; the zero value names nothing and every method that takes it returns an error. ACLTarget is comparable.
func ObjectACL ¶ added in v0.15.0
ObjectACL targets the ACL of one org-scoped object. objectType is its URL segment, normally one of the ACL* constants.
func OrgACL ¶ added in v0.15.0
func OrgACL() ACLTarget
OrgACL targets the ACL of the organization object itself (the client's configured org), served at /organizations/ORG/organizations/_acl.
func UserACL ¶ added in v0.15.0
UserACL targets the ACL of a global user. User ACLs are top-level (/users/NAME/_acl), not org-scoped, and hold users only: erchef refuses a client in them.
func (ACLTarget) ObjectType ¶ added in v0.15.0
ObjectType returns the target's URL segment: the object type for ObjectACL, "organizations" for OrgACL and "users" for UserACL.
type ACLsService ¶
type ACLsService struct {
// contains filtered or unexported fields
}
ACLsService accesses the per-object ACL endpoints. Every Chef object that has identity exposes an _acl subresource; ACLTarget says which one.
func (*ACLsService) Get ¶
Get returns the full ACL of one org-scoped object. It is GetTarget(ctx, ObjectACL(objectType, name)).
func (*ACLsService) GetOrg ¶
GetOrg returns the ACL of the organization object itself. It is GetTarget(ctx, OrgACL()).
func (*ACLsService) GetTarget ¶ added in v0.15.0
GetTarget returns the full five-permission ACL of the target. Each ACE's Actors lists the clients and users together, as erchef reports them.
func (*ACLsService) GetUser ¶
GetUser returns the ACL of a global user object. It is GetTarget(ctx, UserACL(name)).
func (*ACLsService) Grant ¶ added in v0.15.0
func (s *ACLsService) Grant(ctx context.Context, t ACLTarget, perm string, actors, groups []string) (changed []string, err error)
Grant adds actors (users and clients, by name) and groups to perm on the target, where perm is one of ACLPerms or "all". It reads the ACL once and writes only the permissions the members were missing from, returning those in ACLPerms order; nil means every member already held perm and nothing was sent.
A failed read is returned unchanged, with nothing written. A failed write returns the permissions already changed and an *ACLChangeError naming the one that failed. A member that does not exist is refused with a 400 (ErrBadRequest).
Grant is a read-modify-write: a concurrent change to the same permission between the read and the write is overwritten.
func (*ACLsService) Revoke ¶ added in v0.15.0
func (s *ACLsService) Revoke(ctx context.Context, t ACLTarget, perm string, actors, groups []string) (changed []string, err error)
Revoke removes actors and groups from perm on the target, where perm is one of ACLPerms or "all". It follows Grant's rules: one read, a write for each permission that held one of the members, and the permissions changed returned in order (nil if none held any).
erchef refuses to take the admins group off the grant permission unless the caller is the superuser, with a 403 (ErrForbidden) that has nothing to do with the caller's own grant permission.
func (*ACLsService) SetOrgPermission ¶
SetOrgPermission rewrites one permission's ACE on the organization object. It is SetTargetPermission(ctx, OrgACL(), perm, ace).
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 org-scoped object. It is SetTargetPermission(ctx, ObjectACL(objectType, name), perm, ace).
func (*ACLsService) SetTargetPermission ¶ added in v0.15.0
func (s *ACLsService) SetTargetPermission(ctx context.Context, t ACLTarget, perm string, ace *ACE) error
SetTargetPermission rewrites one permission's ACE on the target. 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, or use Grant and Revoke.
Nil Actors/Groups slices are coerced to empty arrays so the server does not reject the request for a null member list. The server refuses a member that does not exist with a 400 (ErrBadRequest).
func (*ACLsService) SetUserPermission ¶
SetUserPermission rewrites one permission's ACE on a global user object. It is SetTargetPermission(ctx, UserACL(name), perm, ace).
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.
func (*Client) ClientName ¶ added in v0.15.0
ClientName returns the client or user name requests are signed as.
func (*Client) Org ¶ added in v0.15.0
Org returns the organization the client's org-scoped requests go to.
func (*Client) ServerAPIVersion ¶ added in v0.15.0
ServerAPIVersion asks the server which API versions it supports, with a GET of the top-level /server_api_version, the cheapest request that reports it (erchef accepts it from any authenticated requestor). The range comes from the body, or from the response header when the body lacks it; Request and Response come from the header, falling back to the body. A response with no range in either is ErrNoServerAPIVersion, never a version of 0, matching the false Response.ServerAPIVersion reports for it.
Every response carries the same header, so a caller that has just made another request can read it from that Response instead.
func (*Client) ServerURL ¶ added in v0.15.0
ServerURL returns the base server URL the client was built with (scheme://host[:port], any trailing slash trimmed). Pair it with Org and FormatServerURL for the combined https://host/organizations/<org> form.
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.
func (CookbookArtifactListEntry) Has ¶ added in v0.15.0
func (e CookbookArtifactListEntry) Has(identifier string) bool
Has reports whether identifier is among the entry's versions. Paired with CookbookArtifacts.List it tells whether the server already holds an artifact a Policyfile lock pins.
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) DottedIdentifier ¶ added in v0.15.0
func (l CookbookLock) DottedIdentifier() string
DottedIdentifier returns the lock's dotted_decimal_identifier (the identifier rendered as a cookbook version, e.g. "1234.5678.9012"), falling back to its identifier when the lock has none. It names the directory a cookbook occupies in a legacy-layout policy export, cookbooks/NAME-DOTTED_IDENTIFIER; chef-cli's current layout is cookbook_artifacts/NAME-IDENTIFIER.
func (CookbookLock) GitRef ¶ added in v0.15.0
func (l CookbookLock) GitRef() string
GitRef returns the git revision to check out for a git-sourced lock: the first non-empty string among the source_options "revision" (the resolved commit, which chef-cli always records), "ref", "tag" and "branch". It returns "" when there is none.
func (CookbookLock) GitSubdir ¶ added in v0.15.0
func (l CookbookLock) GitSubdir() string
GitSubdir returns the source_options "rel": the cookbook's directory within its git repository, or "" when the cookbook is the repository root. It comes from an untrusted lock, so confine it to the checkout before use.
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 or list naming the
// libraries chef-client loads eagerly; nil leaves Chef's default (true).
// ParseMetadataRb stores a list as []string, JSON decoding as []any.
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.
func LoadCookbookMetadata ¶ added in v0.15.0
func LoadCookbookMetadata(dir string) (*CookbookMetadata, error)
LoadCookbookMetadata reads the cookbook metadata in dir. Like Chef's CookbookVersionLoader, metadata.json takes precedence over metadata.rb; see ParseMetadataJSON and ParseMetadataRb. With neither file the error wraps fs.ErrNotExist. As ParseMetadataRb does, it returns the metadata together with an error wrapping ErrMetadataVersionNotLiteral when metadata.rb computes its version.
Values are returned as the file sets them: nothing is defaulted, so an unset Name or Version is empty (see CompiledJSON for Chef's defaults).
func ParseMetadataJSON ¶ added in v0.15.0
func ParseMetadataJSON(data []byte) (*CookbookMetadata, error)
ParseMetadataJSON decodes a compiled metadata.json. Its dependencies are read the way Chef's Metadata#from_hash does (handle_incorrect_constraints): a legacy one-element constraint array ({"apt": [">= 1.0"]}) is unwrapped. Chef turns an empty or multi-element array into [], which the server rejects, so that is an error here. Every other value is kept as written, as from_hash keeps it.
func ParseMetadataRb ¶ added in v0.15.0
func ParseMetadataRb(data []byte) (*CookbookMetadata, error)
ParseMetadataRb statically extracts metadata from a metadata.rb. It is Ruby and is never evaluated, so only calls whose arguments are all literals are recognized, with the arguments Chef::Cookbook::Metadata's DSL accepts:
name, description, long_description, maintainer, maintainer_email, license, source_url, issues_url 'string' version 'x.y.z' | 'x.y' depends, supports, provides 'name'[, 'constraint'] chef_version, ohai_version 'requirement'[, ...] gem 'name'[, 'requirement', ...] recipe 'name', 'description' privacy true | false eager_load_libraries true | false | 'glob' | ['glob', ...]
Arguments may be parenthesized; strings may be single-quoted, or double-quoted without interpolation or escapes other than \" and \\; a symbol (:apt, :"apt") reads as its name; a # comment may end any line. A call may continue onto following lines after a trailing comma or an open parenthesis or bracket, as Ruby reads it (see metadataRbStatements).
A statement whose arguments are not all literals (a computed value, interpolation, a trailing conditional) is skipped, as is any other method, which Chef's method_missing ignores too; metadata.json is the way to supply metadata this cannot see. The one exception is version: a version that is set but cannot be read returns the metadata parsed, with Version empty, and an error wrapping ErrMetadataVersionNotLiteral, since treating it as unset would publish the cookbook as 0.0.0. A later literal version call replaces a computed one, as it would in Ruby.
Recognized values are normalized as Chef::Cookbook::Metadata stores them (version "1.2" is "1.2.0", constraint "1.2" is "= 1.2", requirement "16" is "= 16"), and a call Chef would raise on is an error: a malformed version or constraint, more than one constraint, a literal argument of the wrong type or number, or depends naming the cookbook itself (compared, as Chef does, with the name declared so far).
func (*CookbookMetadata) CompiledJSON ¶ added in v0.15.0
func (md *CookbookMetadata) CompiledJSON() ([]byte, error)
CompiledJSON returns md as the metadata.json Chef compiles from a metadata.rb: what `knife cookbook metadata` writes, what a cookbook shared to Supermarket carries, and what chef-cli writes into an exported Policyfile repository. It has every field Chef::Cookbook::Metadata#to_h writes, in that order, and fills anything unset with Chef's default: license "All rights reserved", version "0.0.0", eager_load_libraries true, empty strings, and {} or [] for the maps and lists. Values are otherwise written as they are, so metadata parsed by ParseMetadataRb comes out normalized as Chef would write it. Attributes and Groupings, which Chef no longer reads or writes, are left out.
Chef requires a name (Metadata#valid?), so an empty Name is an error; knife uses the cookbook's directory name when metadata.rb sets none. The output is indented by two spaces and ends in a newline. Unlike Go's default, <, > and & are not escaped, as Chef's encoder does not; map keys are sorted, where Chef keeps the order metadata.rb declared them in.
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 its files to destDir (see DownloadFiles). version may be LatestVersion. To learn the resolved version before choosing destDir, Get the manifest and pass it to DownloadFiles instead, which saves fetching it twice.
func (*CookbooksService) DownloadFiles ¶ added in v0.15.0
DownloadFiles writes every file of an already-fetched cookbook manifest (a Cookbooks.Get or CookbookArtifacts.Get result) to destDir, recreating the path hierarchy. File content is fetched from the manifest's pre-signed bookshelf URLs using a plain (unsigned) HTTP GET, matching the upload path in sandboxes.go; no API request is made. Each file is verified against the manifest's MD5 checksum and written atomically; files already in destDir with a matching checksum are skipped.
Nothing is written outside destDir. Besides rejecting manifest paths that leave it, writes go through an os.Root on destDir: a symlink already under destDir may point elsewhere inside it, but one pointing out of it fails the download (a directory) or is replaced by the downloaded file (a file).
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: "" or "all" for every version, or "n" for the n newest; anything else is rejected before a request is sent. erchef ignores num_versions on this endpoint, so the client applies the limit. Versions are newest-first.
func (*CookbooksService) List ¶
func (s *CookbooksService) List(ctx context.Context) (map[string]CookbookListEntry, *Response, error)
List returns every cookbook with only its latest version (GET /cookbooks). It is ListVersions(ctx, ""): the Chef Server lists one version per cookbook unless asked for more.
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) ListVersions ¶ added in v0.15.0
func (s *CookbooksService) ListVersions(ctx context.Context, numVersions string) (map[string]CookbookListEntry, *Response, error)
ListVersions returns every cookbook with up to numVersions of its versions (GET /cookbooks?num_versions=N): "all" for every version, "n" for the n newest, or "" for the server default of one. Anything else is rejected before a request is sent. Each entry's versions are newest-first, compared with CompareCookbookVersions, whatever order the server sent them in.
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) Content ¶ added in v0.15.0
func (i DataBagItem) Content() map[string]any
Content returns a copy of the item's own values: every key except "id" and the plaintext "chef_type"/"data_bag" keys a Chef Server adds to the items it echoes back or returns from search. An encrypted value under one of those two names is kept, as Decrypt keeps it. Use it to show or compare what an item holds without its bookkeeping.
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 ErrMissingDataBagItemID error if the item fails Validate, and ErrAlreadyEncrypted if any non-"id" value is already a well-formed encryption wrapper (see IsEncrypted for what counts as one). The second check is deliberately wider than IsEncrypted, which needs every value to be a wrapper: an encrypted item with one plaintext key added would otherwise have its ciphertext encrypted again. A plaintext value cannot trip it by accident, since a wrapper is a map with a numeric version of 1, 2, or 3, string "encrypted_data" and "iv", and the version's "hmac" or "auth_tag".
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.
func (DataBagItem) Validate ¶ added in v0.15.0
func (i DataBagItem) Validate() error
Validate reports whether the item can be written to a Chef Server: it returns ErrMissingDataBagItemID unless the item has a non-empty string "id". Create, Update and Encrypt run the same check; call Validate to vet an item (say, one a user just edited) before doing anything else with it.
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. It returns an ErrMissingDataBagItemID error, without sending anything, if the item fails Validate.
func (*DataBagItemsService) CreateEncrypted ¶ added in v0.15.0
func (s *DataBagItemsService) CreateEncrypted(ctx context.Context, item DataBagItem, secret []byte) (DataBagItem, *Response, error)
CreateEncrypted encrypts a plaintext item with secret (see DataBagItem.Encrypt) and adds it to the bag. The item is not modified. Nothing is sent if the item fails Validate or is already encrypted (ErrAlreadyEncrypted). The returned item is the server's echo, which is the encrypted item as stored.
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) GetDecrypted ¶ added in v0.15.0
func (s *DataBagItemsService) GetDecrypted(ctx context.Context, id string, secret []byte) (DataBagItem, *Response, error)
GetDecrypted retrieves an encrypted item and decrypts it with secret (see DataBagItem.Decrypt). A plaintext item yields an ErrNotEncrypted error and a wrong secret an ErrDataBagAuth error; the item is nil in both cases, and the Response is the GET's.
func (*DataBagItemsService) Update ¶
func (s *DataBagItemsService) Update(ctx context.Context, item DataBagItem) (DataBagItem, *Response, error)
Update replaces an existing item. It returns an ErrMissingDataBagItemID error, without sending anything, if the item fails Validate.
func (*DataBagItemsService) UpdateEncrypted ¶ added in v0.15.0
func (s *DataBagItemsService) UpdateEncrypted(ctx context.Context, item DataBagItem, secret []byte) (DataBagItem, *Response, error)
UpdateEncrypted encrypts a plaintext item with secret and replaces the stored item with it, like CreateEncrypted does for a new one. An edit is GetDecrypted, a change to the plaintext, then UpdateEncrypted.
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. numVersions is as for ListCookbooks, except that "" means every version (the server default here). Versions are newest-first.
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 of one, "all" for every version, or "n" for the n newest; anything else is rejected before a request is sent. Versions are newest-first.
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) ServerMessage ¶ added in v0.15.1
func (e *ErrorResponse) ServerMessage() string
ServerMessage returns what the server said, its Messages joined with "; ", without Error's "cinc: METHOD PATH: CODE:" prefix or the 401 hint. It is "" when the server sent no message (or e is nil), so a caller can fall back to its own wording.
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.
func (*Group) UnmarshalJSON ¶ added in v0.15.0
UnmarshalJSON decodes a group in either shape the server uses. A GET response lists members in top-level users/clients/groups arrays; a PUT body (and erchef's reply to a PUT, which echoes it) nests them in an "actors" object instead. Members found in both places are merged, without duplicates, so a group file written in the PUT shape round-trips through Update instead of emptying the group.
When "actors" is an array it is the flat list a GET adds alongside the typed lists (clients and users on erchef, every member on cinc-server-ng). It cannot be split back by kind and says nothing the typed lists do not, so it is ignored.
type GroupsService ¶
type GroupsService struct {
// contains filtered or unexported fields
}
GroupsService accesses the /groups endpoints.
func (*GroupsService) AddMembers ¶ added in v0.15.0
func (s *GroupsService) AddMembers(ctx context.Context, group string, kind MemberKind, names ...string) (*MemberChange, error)
AddMembers adds names, all of one kind, to group. It reads the group, PUTs it back with the missing names added (skipping the PUT when every name is already a member), then reads it again to report which names the server kept and which it dropped: a name that does not resolve to an existing user, client or group is accepted and silently discarded, so a successful PUT alone does not mean the member was added. A dropped name is not an error; check MemberChange.Dropped.
The update replaces the group's whole membership, so a change another writer makes between the read and the PUT is lost; the Chef API offers no way to make it conditional.
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) RemoveMembers ¶ added in v0.15.0
func (s *GroupsService) RemoveMembers(ctx context.Context, group string, kind MemberKind, names ...string) (*MemberChange, error)
RemoveMembers removes names, all of one kind, from group, with the same read, PUT and read-back as AddMembers. Names that are not members are reported Unchanged, and a PUT is skipped when none are.
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. KeyScope.Create
// sends it whenever PublicKey is empty.
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. Unless k.PublicKey is set, the server generates the keypair and the response's PrivateKey carries the private half: erchef requires one of public_key or create_key, so create_key is sent whenever no public key is. It also requires expiration_date, so an empty k.ExpirationDate is sent as "infinity". k is not modified.
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. It records each file's path and checksum, not its content, so the files must still be on disk, unchanged, when it is uploaded; a file edited in between fails the upload's Content-MD5 check rather than sending new bytes under the old checksum. 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, opts ...LocalCookbookOption) (*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;
- a symlink to a regular file inside the cookbook is kept under its own path; any other symlink, and any special file, is skipped (see cookbookSymlinkTarget).
Metadata comes from LoadCookbookMetadata: metadata.json when present (complete, as compiled by knife or Berkshelf), and otherwise 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 made absolute, so "." names the cookbook after the working directory (Policies.PushRevision replaces that fallback with the cookbook lock's name). 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, and so, when version is empty, is a metadata.rb that computes its version (ErrMetadataVersionNotLiteral), which would otherwise upload as 0.0.0. Every remaining regular file is checksummed as it is read; its content is not kept, but streamed from disk again by the upload. An empty directory is an error. The selected files are available from Files, and the Policyfile identifier over them from Identifiers. The SkipChefignore option keeps the files chefignore would drop.
func (*LocalCookbook) Files ¶ added in v0.15.0
func (cb *LocalCookbook) Files() []LocalCookbookFile
Files returns the cookbook's files, sorted by Path (byte order), as LocalCookbookFromDir selected them; see there for the rules. Callers that archive, copy or fingerprint a cookbook should use this set, so that what they produce matches what an upload sends. The slice is a copy.
func (*LocalCookbook) Identifiers ¶ added in v0.15.0
func (cb *LocalCookbook) Identifiers() (identifier, dottedDecimal string)
Identifiers returns the cookbook's Policyfile content identifier and its dotted-decimal form, as chef-cli's CookbookProfiler::Identifiers computes them for a Policyfile.lock.json: identifier is the SHA-1 hex of one "path:md5\n" line per file, sorted by path; dottedDecimal reads that hex as three integers of 14, 14 and 12 digits joined by "." (the cookbook_artifacts slug older Chef Servers need). The identifier is computed over Files, so it always describes the files an upload of cb sends.
type LocalCookbookFile ¶ added in v0.15.0
type LocalCookbookFile struct {
// Path is the file's path relative to the cookbook root, with forward
// slashes (e.g. recipes/default.rb). It is the path the file is uploaded,
// archived and fingerprinted under.
Path string
// DiskPath is where the file is read from. For a symlink inside the
// cookbook it is the link, not its target.
DiskPath string
// Checksum is the hex MD5 of the file's content when the cookbook was
// loaded.
Checksum string
}
LocalCookbookFile is one file of a LocalCookbook: exactly the files an upload sends and the Policyfile identifier covers.
type LocalCookbookOption ¶ added in v0.15.0
type LocalCookbookOption func(*localCookbookOptions)
LocalCookbookOption configures LocalCookbookFromDir.
func SkipChefignore ¶ added in v0.15.0
func SkipChefignore() LocalCookbookOption
SkipChefignore makes LocalCookbookFromDir ignore chefignore: no chefignore is read, and files it would exclude are kept. Every other selection rule (root dot-directories, the chef-zero sentinel, symlinks, special files) still applies.
Chef's loader always applies chefignore, and chef-cli has no way to turn it off, so the Identifiers of a cookbook loaded this way are not the Policyfile identifiers chef-cli would compute for it whenever chefignore excludes anything; do not write them into a Policyfile.lock.json. The option is for packaging a cookbook as-is, such as a Supermarket tarball.
type MemberChange ¶ added in v0.15.0
type MemberChange struct {
// Changed names the members the server now has (add) or no longer has
// (remove), confirmed by reading the group back.
Changed []string
// Unchanged names those already as asked before the change: already a
// member for an add, not a member for a remove. They are not sent.
Unchanged []string
// Dropped names the changes the server accepted but did not apply, seen
// when the group is read back. On an add these are names the server
// could not resolve: erchef (and cinc-server-ng) answer a PUT naming an
// actor or group that does not exist with success and silently leave it
// out. On a remove these are members still present afterwards, which
// only a concurrent writer re-adding them should cause.
Dropped []string
}
MemberChange reports what AddMembers or RemoveMembers did with each name it was given. Every name lands in exactly one list, in the order given, with repeats counted once.
type MemberKind ¶ added in v0.15.0
type MemberKind string
MemberKind selects one of a group's three member lists.
const ( MemberUser MemberKind = "user" MemberClient MemberKind = "client" MemberGroup MemberKind = "group" )
The member kinds a group holds.
func ParseMemberKind ¶ added in v0.15.0
func ParseMemberKind(s string) (MemberKind, error)
ParseMemberKind reads a member kind from its singular or plural name ("user" or "users", and so on).
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 entries to the node's run list, preserving existing entries and their order. The result is normalized the way the Chef Server stores it (see NormalizeRunList), so "nginx" is not added beside a stored "recipe[nginx]", and bare entries already in the list are qualified.
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) AttributeScalar ¶ added in v0.15.1
AttributeScalar resolves Attribute and reports its value as a string when it is a scalar: a string is returned as-is, a bool or number is formatted (a JSON number without an exponent, so 1700000000 stays "1700000000"), and a non-empty array yields its first element under the same rules. It returns ("", false) when the attribute is absent, null, a map, an empty array, or an array whose first element is none of those scalars, so a caller can tell "cloud" (an object) from a usable host name instead of receiving Go's "map[...]" text.
func (*Node) AttributeString ¶
AttributeString resolves Attribute and coerces the result to a string with AttributeScalar's rules, returning "" when the attribute is absent or is not a scalar (a map, null, or an array that does not lead with a scalar). This mirrors how Chef tooling reads a single scalar attribute (e.g. fqdn) that may be stored as a one-element array.
func (*Node) EnvironmentName ¶ added in v0.15.0
EnvironmentName returns the node's chef_environment, or "_default" when it is unset, which is the environment the Chef Server assigns such a node.
func (*Node) LastCheckin ¶ added in v0.15.0
LastCheckin returns when the node last completed a chef-client run, read from automatic.ohai_time (Unix seconds as a float, set by Ohai on each run). It accepts the value as any JSON-decoded numeric shape (float64, json.Number, int, int64) and reports false when the attribute is absent, not a number, or not positive, as on a node that has never checked in.
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 entries from the node's run list, comparing normalized forms, so "nginx" removes a stored "recipe[nginx]" and vice versa. The remaining list is normalized as well.
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.
func (*NodesService) Modify ¶ added in v0.15.0
func (s *NodesService) Modify(ctx context.Context, name string, fn func(*Node) error) (*Node, bool, error)
Modify fetches the named node, applies fn to it, and saves the result, returning the node the server holds afterwards and whether a PUT was sent.
When fn leaves the node's JSON encoding unchanged, no PUT is sent and the fetched node is returned with false. fn must not rename the node: Modify returns an error without saving if Name changed. An error from fn aborts Modify before the PUT and is returned as-is. A PUT that fails still reports true, since the server may have applied it.
The Chef Server has no optimistic concurrency control on nodes: there is no revision or ETag to make the PUT conditional, so a write that lands between the GET and the PUT (a chef-client run finishing, say, which saves the whole node) is overwritten, and vice versa.
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 how many times a failed request is retried: a GET after a 5xx or a network error, any other method after a 503. The default is 2.
func WithRootCAs ¶ added in v0.15.0
WithRootCAs verifies the server's certificate against pool instead of the system roots, for a server behind a private CA or with a self-signed certificate. To trust extra CAs as well as the system ones, start the pool from x509.SystemCertPool. A nil pool is ignored.
Unlike building your own client for WithHTTPClient, it keeps the client the library would otherwise use, 30s timeout included. With WithHTTPClient it applies to a copy of that client's transport, keeping its tuning and TLS settings (a RoundTripper that is not an *http.Transport is replaced by a copy of http.DefaultTransport, as with WithSkipTLSVerify); the caller's client is not modified. With WithSkipTLSVerify(true) both are set, and as nothing is verified the pool has no effect. Cookbook file transfers trust the pool too.
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) (*PushResult, *Response, error)
PushRevision deploys a Policyfile lock to a policy group: it uploads each cookbook the lock pins as a cookbook artifact (under the lock's name and 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 (and validated, see ParsePolicyfileLock) 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. The caller's LocalCookbooks are not modified.
Each artifact is uploaded under its cookbook-lock name, since that is the name chef-client resolves the lock's run list against. A cookbook whose name LocalCookbookFromDir took from its directory (its metadata declares none) is renamed to the lock's; one whose name or metadata name is a different cookbook is an error, as is one whose version differs from the lock's, since the lock would then pin an artifact that is not the cookbook it describes. All of this is checked before anything is sent.
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 present, since the identifier is a content hash. The PushResult says which were which. 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.
It rejects a lock the server would refuse for its names: the policy name and a non-empty revision_id must be 1 to 255 of A-Z, a-z, 0-9, _, -, : and .; each cookbook lock name must be A-Z, a-z, 0-9, _, - and . only; and a non-empty cookbook lock identifier follows the policy name rule. A missing revision_id or identifier is left for the server (or PushRevision) to refuse, so a partial lock can still be inspected.
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 PushResult ¶ added in v0.15.0
type PushResult struct {
// Revision is the server's answer to the policy group association.
Revision *PolicyRevision
// Uploaded names the cookbook locks whose artifacts this push uploaded,
// sorted. It is never nil.
Uploaded []string
// AlreadyPresent names the cookbook locks whose artifacts the server
// already held under the locked identifier, including one a concurrent
// push stored first (answered with 409), sorted. It is never nil.
AlreadyPresent []string
}
PushResult reports what PoliciesService.PushRevision did.
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.
func (*Response) ServerAPIVersion ¶ added in v0.15.0
func (r *Response) ServerAPIVersion() (ServerAPIVersion, bool)
ServerAPIVersion parses the X-Ops-Server-API-Version header a Chef Server sets on every response, a failed request's included, e.g.
{"min_version":"0","max_version":"2","request_version":"1","response_version":"1"}
It reports false when the header is missing or has no usable min_version and max_version, as from a proxy or a server that is not a Chef Server.
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) AddRunListItems ¶ added in v0.15.0
AddRunListItems appends entries to the role's run list, normalized the way the Chef Server stores it (see NormalizeRunList), so an entry already present under either spelling is not duplicated. EnvRunLists is untouched.
func (Role) MarshalJSON ¶
MarshalJSON encodes the role with run_list always present as an array, for the same reason as Node.MarshalJSON.
func (*Role) RemoveRunListItems ¶ added in v0.15.0
RemoveRunListItems removes entries from the role's run list, comparing normalized forms, so "nginx" removes "recipe[nginx]". The remaining list is normalized as well. EnvRunLists is untouched.
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 a partial search: each row comes back as {"url": ..., "data": {key: value}}, with each value read from the object at its attribute path (key -> path). Node paths address the merged attributes (["kernel", "release"], not ["automatic", "kernel", "release"]), because the server projects from the same merged view it indexes. Use UnwrapSearchRow to get at the projected data.
Projection options accumulate: WithPartial and WithPartialPaths each add their keys to the projection, and a later option replaces an earlier one's path for the same key. The caller's map is copied, never modified.
func WithPartialPaths ¶ added in v0.15.0
func WithPartialPaths(paths ...string) SearchOption
WithPartialPaths requests a partial search of dotted attribute paths. Each path is its own result key, split on "." into the attribute path, so WithPartialPaths("kernel.release") projects {"kernel.release": ["kernel", "release"]}. An empty string is skipped. It composes with WithPartial as described there; use WithPartial for a key other than the path itself or for an attribute name that contains a dot.
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) DataBagItems ¶ added in v0.15.0
func (s *SearchService) DataBagItems(ctx context.Context, bag, query string, opts ...SearchOption) iter.Seq2[DataBagItem, error]
DataBagItems returns an iterator over every item in data bag bag matching query. Each row is passed through UnwrapSearchRow, so a full search yields the items themselves rather than their Chef::DataBagItem envelopes, and a partial search yields each item's projected keys (which hold the id only if the projection asks for it). Paging and errors behave as in Nodes.
func (*SearchService) Indexes ¶
Indexes returns the name->URL index of available search indexes (node, role, client, environment, and one per data bag).
func (*SearchService) Nodes ¶ added in v0.15.0
func (s *SearchService) Nodes(ctx context.Context, query string, opts ...SearchOption) iter.Seq2[*Node, error]
Nodes returns an iterator over every node matching query, decoded as a *Node. It pages like All and ends the same way on a failed page, and also ends on a row that does not decode as a node, yielding that error.
A partial search returns projections rather than nodes, so Nodes refuses WithPartial and WithPartialPaths: it yields one error without sending a request.
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 ServerAPIVersion ¶ added in v0.15.0
type ServerAPIVersion struct {
// Min and Max bound the API versions the server supports.
Min, Max int
// Request is the version the request asked for: 0 when it sent none, -1
// when the server could not parse it.
Request int
// Response is the version the server answered with, -1 when it refused
// the request as not acceptable (406).
Response int
}
ServerAPIVersion is a Chef Server's API version negotiation: the range of X-Ops-Server-API-Version values it accepts and what it made of a request.
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.
// Create sends it whenever PublicKey is empty, so it need not be 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. Unless u.PublicKey is set, the server generates the user's "default" keypair and the result's ChefKey.PrivateKey carries the private half, the only chance to capture it: under server API v1 a user created with neither create_key nor public_key gets no key at all, so create_key is sent whenever no public key is. u is not modified.
func (*UsersService) List ¶
List returns the username -> URL index of every user. Typically restricted to the pivotal superuser identity.
func (*UsersService) SetPassword ¶ added in v0.15.0
SetPassword sets a user's password. erchef's user PUT requires display_name and (for a locally authenticated user) email, and replaces the email with whatever it is sent, so a password alone is not a valid update: this GETs the user and PUTs back everything the server returned, less key fields, with the new password. It is not atomic, so a concurrent update to the same user between the two calls is overwritten. Erchef wants at least six characters.
Source Files
¶
- acls.go
- associations.go
- attributes.go
- checksum.go
- chefignore.go
- client.go
- clients.go
- containers.go
- cookbook_artifacts.go
- cookbook_identifier.go
- cookbook_metadata.go
- cookbook_versions.go
- cookbooks.go
- crud.go
- databag_crypto.go
- databag_secret.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
- runlist.go
- sandboxes.go
- search.go
- serverapiversion.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. |